Merging two XML files recursively

I want to combine 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> 

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

Combined 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, merging can be done with any depth of XML.

I searched on Google and did not find a script that worked correctly.

Can you help me?

+7
source share
2 answers

xml2array is a function that converts an XML document into an array. After creating two arrays, you can use array_merge_recursive to combine them. Then you can convert the array back to xml with XmlWriter (it should already be installed).

+4
source

This is a good solution from comments . PHP manual page , also working with attributes:

 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 is also a usage example here.

0
source

All Articles