Update or replace node with xpath

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
vwlssck
Forum Newbie
Posts: 1
Joined: Mon Mar 14, 2005 4:55 am

Update or replace node with xpath

Post by vwlssck »

I'm trying to write a function that uses an xpath expression to find a node in an xml document and then change the textContent of that node with a new value. I have tried different approaches, but I can't get it to work.

First I tried doing it with simpleXML, something like this:

Code: Select all

<?php
function replaceNode($xml, $query, $value){
	$queryResult = $xml->xpath($query);
		
	if ($queryResult){
		echo 'node <i>' .  $query . '</i> exists, replacing value ';
		
		foreach ($queryResult as $node){
			// replacing the value
			$node =$value;		
		}
	}
	
	else {
		// TODO: if query doesn't return node, create new node
	}
	return $xml;
}
?>
I think I made a conceptual mistake here: changing the value of $node doesn't seem to change the value of that node in $xml, it just changes the value of the copy of that node I made.

Then I tried to use the DOM but I got stuck trying to replace the value of the node. I can append the new value to the old value, but I can't figure out how to replace it.

I'm thinking something like DOMCharacterData->replaceData() is the answer here but I'm not sure what DomCharacterData is or how to access it.

I'm kind of new to this and I'm trying to learn more about working with the DOM and simpleXML so it would greatly apreciated if anyone could point me in the right direction. Links to tutorials about using the DOM/simpleXML with PHP 5 would also be great.

Thanks,
Jeroen
Post Reply