PHP: How to replace existing XML node with XMLWriter
I am editing an XML file and need to populate it with data from a database. DOM works but it is unable to scale to several hundreds of MBs so I am now using XMLReader and XMLWriter which can write the very large XML file. Now, I need to select a node and add children to it but I can't find a method to do it, can someone help me out?
I can find the node I need to add children to by:
if ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == 'data')
{
echo 'data was found';
$data = $xmlReader->getAttribute('data');
}
How do I now add more nodes/children to the found node? Again for clarification, this code will read and find the node, so that is done. What is required is how to modify the found node specifically? Is there a way with XMLWriter for which I have not found a method that will do that after reading through the class documentation?
Answer
Solution:
Be default the expanded nodes (missing in your question)
are not editable with XMLReader (makes sense by that name). However you can make the specific
DOMNode
editable if you import it into a newDOMDocument
:You can then perform any DOM manipulation the DOM offers, e.g. for example adding a text-node:
If you prefer SimpleXML for manipulation, you can also import the node into SimpleXML after it has been imported into the
DOMDocument
:An example from above making use of my xmlreader-iterators that just offer me some nicer interface to
XMLReader
:With the following XML document:
The small example code above produces the following output: