importNode is one of the DOM functions in PHP 5 that I struggled with for a while. What I wanted to do was to take an XML node from one document and insert it into another, and somehow that wasn’t particularly easy. I tried using ‘appendChild’ but kept getting ‘wrong document’ error messages. Once it was working it seemed obvious, but the example in the documentation wasn’t entirely clear to me.
As an outline, the steps that need to be gone through are:
- Import the node you want into the destination document. This is done by calling the importNode method and storing the result in a variable (the crucial step). At this stage, the node is in the document, but won’t appear anywhere if you print it out which may seem odd.
- Append the stored node to the destination document in the place you want it
The code then is as follows. This is for taking a complete document and moving it into a new DOMDocument object. The existing xml is assumed to be loaded into $oldXML
$xml = new DOMDocument(); $xmlContent = $xml->importNode($oldXML->documentElement,true); $xml->appendChild($xmlContent);
It is important to use the second parameter ‘true’ in importNode as this tells the method to import all children as well as the selected node. The node that $xmlContent is appended to can be any DOMElement. Note that importNode is a method of the DOMDocument (and must always be) as it is the document as a whole that the new node is being imported into, not a specific node.
importNode in the PHP 5 DOM documentation
appendChild in the PHP 5 DOM documentation
5 thoughts on “Using importNode and appendChild with PHP 5 DOM”
Thanks, this post was really helpful. Much more informative than the documentation I found. 😀
I was having a lot of trouble adding xml to another domdocument. Using the importNode function was the trick. I wish I would have found this sooner.Thanks,Schmalls
Fantastic!!!Tou wonder why this is not mentioned in the online documentation.Thanks very much. This saved me a LOT of work.Johan.
Hey thanks, it really made it clear for me.
Argh, THANK YOU!!! Was pulling my hair out over this.