views:

285

answers:

2

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

This node has a bunch of descendants, and I want to take that entire node (and its descendants) and create a new DOMDocument object from it. I'm not sure how to do this; I tried creating a new DOMDocument and using DOMDocument::importNode(), but this appears to only work if the DOMDocument already has a main document node in it, in which case it appends the imported node as a child of the main document node, which is not what I want -- I want the imported node to BECOME the DOMDocument main node.

Maybe there's 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 its own document), but I don't know of it. I'm relatively new to DOMDocument, although I've used SimpleXMLElement enough to be annoyed by it.

A: 

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

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

I'm unable to try it right now but that should work.

Josh Davis
+1  A: 

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

That worked for me.

Willem