Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks!

like image 255
AlexV Avatar asked Apr 20 '11 19:04

AlexV


Video Answer


2 Answers

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);
$newdoc->documentElement->appendChild($node);

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.

like image 101
Stefan Gehrig Avatar answered Nov 15 '22 03:11

Stefan Gehrig


You need to import it into the target document. See DOMDocument::importNode

like image 27
troelskn Avatar answered Nov 15 '22 04:11

troelskn