I'm trying to combine multiple XML files that have the same structure into one file.
This is the structure of my XML files:
file1.xml:
<root information="file1">
<items>
<item>FOO</item>
<item>BAR</item>
</items>
</root>
file2.xml:
<root information="file2">
<items>
<item>BAR</item>
<item>FOO</item>
</items>
</root>
Using this code I've been able to combine them:
$files= array(
'file1.xml',
'file2.xml'
);
$dom = new DOMDocument();
$dom->appendChild($dom->createElement('root'));
foreach ($files as $filename) {
$addDom = new DOMDocument();
$addDom->load($filename);
if ($addDom->documentElement) {
foreach ($addDom->documentElement->childNodes as $node) {
$dom->documentElement->appendChild(
$dom->importNode($node, TRUE)
);
}
}
}
$dom->save('output.xml');
This works partly but removes the original root element which has the information attribute that I still need. So I would like to keep all the existing root elements but wrap them in a new root element. This is what I would like to end up with:
<files>
<root information="file1">
<items>
<item>FOO</item>
<item>BAR</item>
</items>
</root>
<root information="file2">
<items>
<item>BAR</item>
<item>FOO</item>
</items>
</root>
</files>
But I can't figure out how to append the file. Whatever I try it only ends up at the bottom of the output file instead of appending all old root elements. I'm guessing this is simple as hell but I just can't figure it out. Help much appreciated!
DOMDocumentand not just append them straight into a new file?