Jump to content

Writing to Nodes with simplexml


ameliabob

Recommended Posts

I have not been able to find anything on how to update a node using simplexml. In the following code

$t = "<root><book>Hard Example</book></root>";$xse = simplexml_load_string($t);$tags = $xse->xpath( "book" );echo( "Found ".$tags[0]."<br />" );$tags[0] = "Easy now";echo("tags[0] ".$tags[0]."<br />");echo($xse->asXML());

The xml document does not appear to get updated. Is it that simplexml doesn't allow updating.?

Link to comment
Share on other sites

I already told you that in this topic. The last post in particular.asXML() simply outputs the contents of the XML. You still need to save that contents into a file yourself.

Link to comment
Share on other sites

My question here relates to the line $tag[0] = "Easy Now";This doesn't work. Where have I mistaken the syntax?
You're trying to assign "Easy Now" to a newly created $tag array. It's not going to change the XML.Use the addChild() function.
Link to comment
Share on other sites

The $tag array was created in the xpath statement.
It's an array that contains the information of the nodes, it's not a pointer to the nodes themselves. All you're doing is modifying the array itself, which is independent from the XML. It's just a variable.SimpleXML is a pretty limited library, it can't remove nodes, and I don't think it can modify them either. It can add nodes and attributes though. You should use the DOMDocument class, it's a lot more reliable and flexible, though it requires more XML DOM knowledge.Here's how your application would be done with the DOMDocument class:
$t = "<root><book>Hard Example</book></root>";$xse = new DOMDocument();$xse->loadXML($t);$tags = $xse->getElementsByTagName("book")->item(0)->childNodes;echo( "Found ".$tags->item(0)."<br />" );$tags->item(0)->nodeValue = "Easy now";echo("tags[0] ".$tags->item(0)->nodeValue."<br />");echo($xse->saveXML());

If this doesn't do what you wanted it too, it's probably because you had a wrong XPath expression in your code.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...