ali
ali

Reputation: 11045

PHP - get all XML child nodes of a specific type

I have an XML structure like this:

<root>
    <parent>
        <child name='Child1' />
        <child name='Child2' />
        <subparent>
            <child name='Child3' />
        </subparent>
    </parent>
    <child name='Child4' />
<root>

Using PHP simplexml I am trying o get all the 'child' nodes, no matter what level, and I would like to know if there's a quick function for that, instead of scanning each node of the XML.

Upvotes: 0

Views: 4333

Answers (1)

nickb
nickb

Reputation: 59699

Sure, all you need to do is use an xpath() query on your XML:

$xml = simplexml_load_string( $xml);

foreach( $xml->xpath( '//child') as $child) { 
    $attributes = $child->attributes();
    echo $attributes['name'] . "\n";
}

You can see from this demo that this prints:

Child1 
Child2 
Child3 
Child4

Upvotes: 3

Related Questions