PHP DOMDocument将节点从文档移动到另一个文档

时间:2011-04-20 19:53:34

标签: php domdocument

好的,我正在努力实现这个好几个小时,似乎无法找到解决方案,所以我在这里!

我有2个DOMDocument,我想将文档的节点移动到另一个。我知道两个文件的结构,它们属于同一类型(所以合并它们应该没问题。)

任何人都可以帮助我吗?如果您需要更多信息,请告诉我们。

谢谢!

4 个答案:

答案 0 :(得分:9)

要复制(或)将节点移动到另一个DOMDocument,您必须使用importNode()将节点导入新的DOMDocument。手册中的示例:

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

importNode()的第一个参数是节点本身,第二个参数是一个布尔值,表示是否导入整个节点树。

答案 1 :(得分:2)

您需要将其导入目标文档。见DOMDocument::importNode

答案 2 :(得分:0)

将此代码用于未知的文档结构。

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

答案 3 :(得分:0)

<?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();
    }
?>
相关问题