AlexV AlexV - 1 year ago 83
PHP Question

PHP DOMDocument move nodes from a document to another

OK, I'm trying to achieve this for hours now and can't seem to find a solution so here I am!

I have 2 DOMDocument and I want to move the nodes of a document to the other one. I know the structure of both documents and they are of the same type (so I should have no problem to merge them).

Anyone can help me? If you need more info let me know.


Answer Source

To copy (or) move nodes to another DOMDocument you'll have to import the nodes into the new DOMDocument with importNode(). Example taken from the manual:

$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");
$node = $orgdoc->getElementsByTagName("element")->item(0);

$newdoc = new DOMDocument;
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");

$node = $newdoc->importNode($node, true);

Where the first parameter of importNode() is the node itself and the second parameter is a boolean that indicates whether or not to import the whole node tree.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download