A possible idea would be to :
- Create a new
$destination instance of DOMDocument
- Initialize it with a
<statuses> node
- For each of your 3 XML strings :
- load it to another instance of
DOMDocument : $currentDocument
- find the
<status> node, with $currentDocument->getElementsByTagName or an equivalent
- import the
<status> node you've just found to the $destination document, with $destination->importNode
- When the loop over each XML string is finished, the
$destination document should contain what you wanted, and you can save it, using $destination->saveXML
And here's a quick example of code that could help you understand what I meant :
First, here's the array of XML strings -- I've made them much shorter, but the idea is the same that what you have :
$strings = array(
'<?xml version="1.0" encoding="UTF-8"?>
<statuses type="array"><status>
<id>ID 1</id>
</status></statuses>',
'<?xml version="1.0" encoding="UTF-8"?>
<statuses type="array"><status>
<id>ID 2</id>
</status></statuses>',
'<?xml version="1.0" encoding="UTF-8"?>
<statuses type="array"><status>
<id>ID 3</id>
</status></statuses>',
);
Let's create the destination document, and put a <statuses> tag in it :
$destination = new DOMDocument();
$destination->formatOutput = true;
$destinationStatuses = $destination->createElement('statuses');
$destination->appendChild($destinationStatuses);
Now, we loop over the 3 XML strings :
foreach ($strings as $str) {
$current = new DOMDocument();
$current->loadXML($str);
$currentStatuses = $current->getElementsByTagName('status');
foreach ($currentStatuses as $currentStatus) {
$destinationStatus = $destination->importNode($currentStatus, true);
$destinationStatuses->appendChild($destinationStatus);
}
}
For each string, we :
- Load it to a new
DOMDocument
- Find the
<status> tag(s)
- For each
<status> tag, import it to the destination document
- And add it to its
<statuses> tag
And, finally, if we output the content of the new document :
echo '<pre>' . htmlspecialchars($destination->saveXML()) . '</pre>';
We get :
<?xml version="1.0"?>
<statuses>
<status>
<id>ID 1</id>
</status>
<status>
<id>ID 2</id>
</status>
<status>
<id>ID 3</id>
</status>
</statuses>
i.e. our three <status> from the three original strings have been merged into a single XML Document ;-)