Two steps, prepare the target DOM (add the document element). Load each source XML, traverse the child nodes inside the document element and import them into your target document:
$xmlFiles = [
'/uploads/companyroutes.xml',
'/uploads/companyroutes_core.xml'
];
$targetDom = new DOMDocument();
$targetDom->appendChild(
$targetDom->createProcessingInstruction(
'xml-stylesheet', 'type="text/xml" href="merge2.xsl"'
)
);
$rootNode = $targetDom->appendChild(
$targetDom->createElement('companyroutes')
);
foreach ($xmlFiles as $xmlFile) {
$importDom = new DOMDocument();
$importDom->load($xmlFile);
foreach ($importDom->documentElement->childNodes as $node) {
$rootNode->appendChild($targetDom->importNode($node, TRUE));
}
}
echo $targetDom->saveXml();
An example with XML strings as sources: https://eval.in/97405
Of course you could create a template XML for the target DOM and just load it:
$template = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xml" href="merge2.xsl"?>
<companyroutes/>
XML;
$targetDom = new DOMDocument();
$targetDom->loadXml($template);
$rootNode = $targetDom->documentElement;
...
I would not suggest changing a document. If you build a new document you can repeat the action.