2

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.

2
  • 1
    Your input XML is invalid. The mandatory root element (whatever tag name it has) is missing. SimpleXML fails to parse it. Commented Feb 3, 2011 at 17:23
  • It's interesting to note that because the OP used the mute operator @, the error was suppressed. The mute operator should pretty much never be used, and especially not during development. Commented Feb 4, 2011 at 9:57

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.