Using importNode and appendChild with PHP 5 DOM

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:

  1. 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.
  2. Append the stored node to the destination document in the place you want it

The thing that threw me is that the importNode method doesn’t so much import the node as make a copy of it in the destination document – so the original is actually left untouched. This seems to be standard across XML DOM methods in other languages such as C# and JavaScript.

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);

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”

  1. 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

  2. Fantastic!!!Tou wonder why this is not mentioned in the online documentation.Thanks very much. This saved me a LOT of work.Johan.

Leave a Reply

Your email address will not be published. Required fields are marked *