I have an example where I need to update an XML node based on an XPath. SimpleXMLElement
makes this easy enough by using an XPath to grab the node and then update its value in a pass-by-reference format.
However, this doesn't work at all if the node doesn't actually exist that needs to be updated. Are there any simple ways to automatically generate the XML that matches the XPath if it doesn't exist?
An example:
<example>
<childNode1>green</childNode1>
</example>
Given the XML, I could easily run the xpath command to get the <childNode1>
by loading up the xml into a SimpleXMLElement
and then running $xml->xpath("example/childNode1");
. I could then set the value of the returned SimpleXMLElement
to something new and then save the xml.
However, if I needed to set something like <childNode2>
the $xml->xpath("example/childNode2")
would return nothing and it wouldn't be possible to set the value or confirm that the XML was built.
Is iterating through the XPath and parsing its values the only way to confirm that each child node exists and then build them out as it goes or is there a better way to generate the necessary XPath?