以递归方式合并两个XML文件

时间:2011-06-17 12:22:56

标签: php xml merge simplexml

我想以递归方式将2个XML文件合并为一个。例如:

第一个文件:

<root>
    <branch1>
        <node1>Test</node1>
    </branch1>
    <branch2>
        <node>Node from 1st file</node>
    </branch2>
</root>

第二档:

<root>
    <branch1>
        <node2>Test2</node2>
    </branch1>
    <branch2>
        <node>This node should overwrite the 1st file branch</node>
    </branch2>
    <branch3>
        <node>
            <subnode>Yeah</subnode>
        </node>
    </branch3>
</root>

合并文件:

<root>
    <branch1>
        <node1>Test</node1>
        <node2>Test2</node2>
    </branch1>
    <branch2>
        <node>This node should overwrite the 1st file branch</node>
    </branch2>
    <branch3>
        <node>
            <subnode>Yeah</subnode>
        </node>
    </branch3>
</root>

我希望将第二个文件添加到第一个文件中。当然,可以使用任何深度的XML来完成合并。

我在Google上搜索过,但没有找到一个正常运行的脚本。

你能帮我吗?

2 个答案:

答案 0 :(得分:4)

xml2array是一个将xml文档转换为数组的函数。创建两个数组后,您可以使用array_merge_recursive来合并它们。然后,您可以使用XmlWriter将数组转换回xml(应该已经安装)。

答案 1 :(得分:0)

这是对PHP manual page的评论很好的解决方案,也适用于属性:

function append_simplexml(&$simplexml_to, &$simplexml_from)
{
    foreach ($simplexml_from->children() as $simplexml_child)
    {
        $simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(), (string) $simplexml_child);
        foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
        {
            $simplexml_temp->addAttribute($attr_key, $attr_value);
        }

        append_simplexml($simplexml_temp, $simplexml_child);
    }
} 

还有使用样本。

相关问题