Get list of children in SimpleXMLElement PHP

how to get the list of children in xml-> request-> ABC ABC can have DEF, ZZA, XAS, ETC and I would like to iterate over the list of these children (name required) instead of checking if they exist.

-edit- Note. I am looking for the element name. I found an example that returns an attribute if known. How do I get the tag / element name?

+2


source to share


1 answer


Considering this XML snippet and the code to load it using SimpleXML:

$str = <<<XML
<xml>
    <request>
        <ABC>
            <DEF>glop</DEF>
            <ZZA>test</ZZA>
        </ABC>
    </request>
</xml>
XML;
$xml = simplexml_load_string($str);

      

How about using a method children()

to get a list of all your ABC children and iterate over them using foreach?

This way, for example:



foreach ($xml->request->ABC->children() as $a => $b) {
    echo "$a $b<br />";
}

      

And you get this output:

DEF glop
ZZA test

      

+3


source







All Articles