Creating a DOMDocument from a DOMNode in PHP

I get an XML string from a specific source. I create a DOMDocument object and load an XML string into it (with DOMDocument :: loadXML ()). Then I navigate through the XML document using various methods (e.g. DOMXPath) until I find the node (DOMNode, of course) that I want.

This node has a bunch of descendants, and I want to take this whole node (and its descendants) and create a new DOMDocument object from it. I am not sure how to do this; I tried to create a new DOMDocument and use DOMDocument :: importNode (), but this only works if the DOMDocument already has the main node document in it, in which case it adds the imported node as a child of the main node document, which is not what i want - i want the imported node to become the main DOMDocument node.

There may be an easier way to do this (i.e. an easier way to extract the part of the original XML that I want to turn into my own document), but I don't know about that. I'm relatively new to DOMDocument, although I used SimpleXMLElement to annoy it.

+6
dom xml php domdocument
source share
2 answers

You can also create a new DOMDocument and call appendChild () on it to add a root node:

  $ new = new DomDocument;
 $ new-> appendChild ($ new-> importNode ($ node, true));

It worked for me.

+13
source share

Can't you create a new DOMDocument and load node XML?

$new = new DOMDocument; $new->loadXML($node->ownerDocument->saveXML($node)); 

I can’t try right now, but it should work.

0
source share

All Articles