Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a DOMDocument from a DOMNode in PHP

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.

like image 261
dirtside Avatar asked Feb 10 '10 04:02

dirtside


People also ask

What is DOMDocument() in PHP?

The DOMDocument::getElementsByTagName() function is an inbuilt function in PHP which is used to return a new instance of class DOMNodeList which contains all the elements of local tag name.

How to create dom in PHP?

$dom = new DOMDocument('1.0', 'utf-8'); $element = $dom->createElement('foo', 'me & you'); $dom->appendChild($element); echo $dom->saveXML();

Which PHP DOM function is used to create a new element?

PHP | DOMElement __construct() Function The DOMElement::__construct() function is an inbuilt function in PHP which is used to create a new DOMElement object.

What is Domdoc?

A DomDocument is a container (variable/object) for holding an XML document in your VBA code. Just as you use a String variable to hold a strings value, you can use a DomDocument to hold an XML document. (for a complete list of a DomDocuments properties, see halfway down this page)


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

That worked for me.

like image 121
Willem Avatar answered Oct 13 '22 00:10

Willem