I have an XML file (example below) and it is sitting somewhere on the net. When I import it using SimpleXML like so $sXML = @simplexml_load_file( $url );
, the contents of the files are converted in the simple XMl objects.
<?xml version="1.0" encoding="UTF-8"?>
<title>Test</title>
<description>Test Description</description>
<item id="500">
<title>Item Title</title>
<description>Item Description</description>
</item>
<item id="501">
<title>Item Title</title>
<description>Item Description</description>
</item>
I would like to add a new set of parents. One at root level and the other that contains "item" so that it looks like the XML file below:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<title>Test</title>
<description>Test Description</description>
<content>
<item id="500">
<title>Item Title</title>
<description>Item Description</description>
</item>
<item id="501">
<title>Item Title</title>
<description>Item Description</description>
</item>
</content>
</data>
How is this possible using SimpleXML or any other way?
Thanks for all the help.
Note that the input XML given as example is invalid. It is mandatory to have a single root node. That said, here is a possible solution:
$sXML = simplexml_load_file($url);
$nonItems = '';
$items = '';
foreach ($sXML as $child) {
if ($child->getName() == 'item') {
$items .= $child->asXML();
} else {
$nonItems .= $child->asXML();
}
}
$xml = sprintf('<?xml version="1.0"?><data>%s<content>%s</content></data>',
$nonItems, $items);
// echo simplexml_load_string($xml)->asXML();