将两个xml文档合并为一个,用新的根替换原来的根元素


Merge two xml documents into one replacing original root elements with new root

我有两个XML数据源,我想用PHP脚本将它们合并到一个XML文档中。

第一个XML源文档

<book>
 <id>1</id>
 <title>Republic</title>
</book>

第二个源XML文档

<data>
 <author>Plato</author>
 <language>Greek</language>
</data>

我想把这两个组合起来得到

<book>
 <id>1</id>
 <title>Republic</title>
 <author>Plato</author>
 <language>Greek</language>
</book>
但是我得到的是
<book>
 <id>1</id>
 <title>Republic</title>
<data>
 <author>Plato</author>
 <language>Greek</language>
</data></book>

这是我的代码

$first = new DOMDocument("1.0", 'UTF-8');
$first->formatOutput = true;
$first->loadXML(firstXML);
$second = new DOMDocument("1.0", 'UTF-8');
$second->formatOutput = true;
$second->loadXML(secondXML);
$second = $second->documentElement;
$first->documentElement->appendChild($first->importNode($second, TRUE));
$first->saveXML();
$xml = new DOMDocument("1.0", 'UTF-8');
$xml->formatOutput = true;
$xml->appendChild($xml->importNode($first->documentElement,true));
return $xml->saveXML();

这就是你需要的。必须使用loop

添加节点
        $first = new DOMDocument("1.0", 'UTF-8');
        $first->formatOutput = true;
        $first->loadXML($xml_string1);

        $second = new DOMDocument("1.0", 'UTF-8');
        $second->formatOutput = true;
        $second->loadXML($xml_string2);
        $second = $second->documentElement;
        foreach($second->childNodes as $node)
        {
           $importNode = $first->importNode($node,TRUE);
           $first->documentElement->appendChild($importNode);
        }

        $first->saveXML();
        $xml = new DOMDocument("1.0", 'UTF-8');
        $xml->formatOutput = true;
        $xml->appendChild($xml->importNode($first->documentElement,true));
        return $xml->saveXML();

这是因为您的$second var,最初是DOMDocument,被设置为$second->documentElement,这是根节点。

在本例中,根节点是<data>节点。

因此,当您appendChild $second时,深度参数设置为TRUE,它将追加<data>节点及其所有子节点。

解决方案:相反,您应该附加此$second的所有子节点。

foreach($second->childNodes as $secondNode){
    $first->documentElement->appendChild($secondNode);
}