0

I'm trying to update XML document. I start with a string that contains XML.

I'm loading that string to SimpleXMLElement object:

$xmlDoc = simplexml_load_string($my_xml_string);

I find a node that I would like to update like so:

$node= $xmlDoc->xpath("//nodename[@node_attribute='{$search_attribute_value}']");

Now I would like to update the node_attribute attribute. I try to do $node['node_attribute']=$new_attribute_value however $node is it's own object and this doesn't update the $xmlDoc object.

How do I find and update attribute value in the $xmlDoc?

2 Answers 2

2

The $node you have there is actually an array of nodes. If you know you've only got one to update you can:

$node[0]['node_attribute'] = $new_attribute_value;

More appropriate may be:

$nodes = $xmlDoc->xpath("//nodename[@node_attribute='{$search_attribute_value}']");
foreach ($nodes as $node) {
    $node['node_attribute'] = $new_attribute_value;
}

And everything will be updated as expected.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah adding an index to that node did the trick. $node[0]['node_attribute']=$new_attribute_value; Not sure what was happening before.
@dev.e.loper Also note if your node has a text portion, you will use $node[0]->{'0'}, as such written in here.
0

Untested, but you should try like this.

$nodename->attributes()->node_attribute = $new_attribute_value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.