PHP DOMDocument move nodes from a document to anot

2019-06-22 01:33发布

问题:

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!

回答1:

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.



回答2:

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



回答3:

Using this code for unknown structure of document.

$node = $newDoc->importNode($oldDoc->getElementsByTagName($oldDoc->documentElement->tagName)->item(0),true);


回答4:

<?php
    protected function joinXML($parent, $child, $tag = null)
    {
        $DOMChild = new DOMDocument;
        $DOMChild->loadXML($child);
        $node = $DOMChild->documentElement;

        $DOMParent = new DOMDocument;
        $DOMParent->formatOutput = true;
        $DOMParent->loadXML($parent);

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

        if ($tag !== null) {
            $tag = $DOMParent->getElementsByTagName($tag)->item(0);
            $tag->appendChild($node);
        } else {
            $DOMParent->documentElement->appendChild($node);
        }

        return $DOMParent->saveXML();
    }
?>