Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two XML files recursively

I want to merge 2 XML files into one recursively. For example :

1st file :

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

2nd file :

<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>

Merged file :

<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>

I want the second file to be added to the first file. Of course the merging can be done with any depth of the XML.

I have searched on Google and didn't found a script that worked properly.

Can you help me please ?

like image 443
Kyryus Avatar asked Jun 17 '11 12:06

Kyryus


1 Answers

xml2array is a function that converts an xml document to an array. Once the two arrays are created, you can use array_merge_recursive to merge them. Then you can convert the array back to xml with XmlWriter (should already be installed).

like image 84
Explosion Pills Avatar answered Sep 29 '22 23:09

Explosion Pills