9

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 ?

Kyryus
  • 121
  • 1
  • 5
  • 2
    Here is a very similar question to what you just asked. There are a couple of solutions mentioned on it - http://stackoverflow.com/questions/648471/merge-two-xml-files-in-java. – Perception Jun 17 '11 at 12:33
  • 1
    Yah but it is in Java :D – Kyryus Jun 17 '11 at 12:48
  • possible duplicate of [SimpleXML: append one tree to another](http://stackoverflow.com/questions/3418019/simplexml-append-one-tree-to-another) – Line Feb 28 '14 at 15:29

2 Answers2

4

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

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

This is nice solution from comment on PHP manual page, working also with attributes too:

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

There also is sample of usage.

Line
  • 1,529
  • 3
  • 18
  • 42