好吧,我试着实现这个几个小时了,现在似乎找不到解决方案,所以我在这里!
我有2个DOMDocument,我想把一个文档的节点移动到另一个。我知道这两个文档的结构,它们是相同的类型(所以合并它们应该没有问题)。
有人能帮我吗?如果你需要更多的信息,请告诉我。
谢谢!
要复制(或)移动节点到另一个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()
的第一个参数为节点本身,第二个参数为布尔值,表示是否导入整个节点树。
您需要将其导入目标文档。看到DOMDocument: importNode
对未知结构的文档使用此代码。
$node = $newDoc->importNode($oldDoc->getElementsByTagName($oldDoc->documentElement->tagName)->item(0),true);
<?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();
}
?>