'Removing a ROOT node using SimpleXML

I have have the following code:

<nutrition>
    <code>
        <lol1>energy</lol1>
        <lol2>protein</lol2>
        <lol3>fat</lol3>
    </code>
</nutrition>

and I want:

<code>
    <lol1>energy</lol1>
    <lol2>protein</lol2>
    <lol3>fat</lol3>
</code>

Is there any SimpleXML function to remove the ROOT node?

(I know there is some DOM library, however I don't want to use it)



Solution 1:[1]

I know there is some DOM library, however I don't want to use it

It is not technically possible in PHP SimpleXML to rename the document element (you call that root node).

And actually you can't rename it with DOMDocument either. But unlike in SimpleXML you can replace an element with DOMDocument::replaceChild easily.

With the given input:

$buffer = <<<XML
<nutrition>
    <code>
        <lol1>energy</lol1>
        <lol2>protein</lol2>
        <lol3>fat</lol3>
    </code>
</nutrition>
XML;

First create the DOMDocument:

$doc                     = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->formatOutput       = true;

Then load your XML (for example as string $buffer) here:

$doc->loadXML($buffer);

Obtain the soon to become document element:

$code = $doc->documentElement->getElementsByTagName('*')->item(0);

Replace the document element and output to show it worked:

$doc->replaceChild($code, $doc->documentElement);
$doc->save('php://output');

This gives the following output:

<?xml version="1.0"?>
<code>
  <lol1>energy</lol1>
  <lol2>protein</lol2>
  <lol3>fat</lol3>
</code>

And that's it. Hope this is still helpful even you seem to not like DOMDocument. But don't fear it, it's a sister library of SimpleXMLElement.

Solution 2:[2]

Yes, you can:

$xmlstr = <<<'XML'
<nutrition>
    <code>
        <lol1>energy</lol1>
        <lol2>protein</lol2>
        <lol3>fat</lol3>
    </code>
</nutrition>
XML;

$xml = new SimpleXMLElement($xmlstr);
foreach ($xml->xpath('/nutrition/child::code[1]') as $node) {
    $unwrappedXml = new \SimpleXMLElement($node->asXML());
    break;
}

echo $unwrappedXml->asXML();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hakre
Solution 2 Daniel-KM