Reputation: 283
I have a bunch of XML files that look like this:
<widget>
...
</widget>
In PHP, I need to combine them into a single XML file like so:
<widgets>
<widget>
...
</widget>
<widget>
...
</widget>
<widget>
...
</widget>
</widgets>
This is trivial to do with glob
and file_[get/put]_contents
, but I'd like to do it properly with DOMDocument because there's more to it than this. I've created a DOMDocument
instance and a wrapping element, and in a loop, use appendChild()
to append each XML file inside said element. Unfortunately I keep getting a variety of errors thrown and I just can't put something together that works. Any ideas?
Upvotes: 0
Views: 66
Reputation: 2761
If you want to use DOMDocument to load the other files, they will need to be valid XML files in their own right - ie have a single root node. Once you have that, the following code should work:
// Given that $files is a list of file names of xml files to add
// Each xml file must be xml conformant - ie a single root node
$dest = new DOMDocument;
$root = $dest->createElement ('widgets');
$dest->appendChild ($root);
foreach ($files as $fn)
{
$doc = new DOMDocument ();
if ($doc->load ($fn))
{
foreach ($doc->documentElement->childNodes as $child)
{
// Copy deep for destination document
$child = $dest->importNode ($child, true);
$root->appendChild ($child);
}
}
}
Upvotes: 1