How to remove root node from XML

I had an issue few days ago with a web service implementation, only to find how simple and elegant the solution was.

Context

In order to make it easy I made a wrapper allowing me to call the different methods of the web service from the same class.
Which lead me to create a SimpleXMLElement with <root></root> as my XML root, then later I could use addChild method to add the web service required node and namespace :

<root>
    <auth></auth>
</root>

------- OR -------

<root>
    <get></get>
</root>

------- OR -------

<root>
    <set></set>
</root>

Problem is : <root></root> is not a valid root node and the web service call failed.
Solution is : simply remove that root node and send the rest of the XML.

But at first it was not so simple, posts I've visited on stackoverflow mostly suggested too horrible or too complicated (DOMDocument, loops, array conversion, ...) piece of code too just remove the root node from a SimpleXMLElement instance.

XPATH

In the end, the solution was so simple, use SimpleXMLElement::xpath method.

Example :

$xml_string = <<<XML
<root>
    <movies>
        <movie>
            <title>Titanic</title>
            <year>1997</year>
        </movie>
        <movie>
            <title>Forrest Gump</title>
            <year>1994</year>
        </movie>
        <movie>
            <title>Alien</title>
            <year>1979</year>
        </movie>
    </movies>
</root>
XML;

$xml = new SimpleXMLElement($xml_string);

$only_movies_nodes = $xml->xpath('movies');

$only_movies = $only_movies_nodes[0];

var_dump(
    $only_movies->asXML()
);

The above example will output :

string '<movies>
        <movie>
            <title>Titanic</title>
            <year>1997</year>
        </movie>
        <movie>
            <title>Forrest Gump</title>
            <year>1994</year>
        </movie>
        <movie>
            <title>Alien</title>
            <year>1979</year>
        </movie>
    </movies>' (length=319)

Done !



Blog Comments powered by Disqus.