Search code examples
phpxmlxpathsimplexml

Is there a way to get simple XML child elements by node name?


In PHP, is there an existing method to get one or more child elements by node name (recursively) or would you have to write a function for that yourself?

For example, this is my XML:

<parent>
    <child>
        <grandchild>Jan</grandchild>
        <grandchild>Kees</grandchild>
    </child>
</parent>

And I'm looking for a method that returns something like: Array( [0] => 'Jan', [1] => 'Kees' )

by means of calling something like:

$grandchildren = $xml->children('grandchild');

The above does exist according to documentation but only for namespaces.

e: The accepted answer below worked. This is what I ran to test it.

$xml = '
    <parent>
        <child>
            <grandchild>Jan</grandchild>
            <grandchild>Kees</grandchild>
        </child>
    </parent>';

$L_o_xml = new SimpleXMLElement($xml);

$L_o_child = $L_o_xml->xpath('//grandchild');

foreach( $L_o_child as $hi ){
   print "\n".(string)$hi;
}

Simply printed:

Jan
Kees

Solution

  • You can use $xml->xpath() to select nodes in a variety of complex ways:

    $xml->xpath('//grandchild');   // select all  grandchild  elements in the document