Search code examples
phpsimplexml

PHP SimpleXML - Loop and check name of element


In my example, I have produce in an XML file. As I loop through it, I need to check what the name of the first top-level element is to determine what to do with it.

Here is my code and pseudo code:

        $xml = simplexml_load_file($xmlfile);

        $produce = array();
        $i = 0;

        foreach ($xml as $prod) {
            //this works if I know there is fruit
            $nm = $xml->fruit->name; //apple
            $produce[i]['name'] = $nm

            //what I want is this
            if (the first level element name is 'fruit') then
               do something fruity like $produce[i]['type'] = 1
            else if (the first level element name is 'vegetable' then
               do something else like $produce[i]['type'] = 2

        $counter++;
        }

We're all thinking "why is fruit/veg not an attribute of the element?" - I have no control over the input.

How can I test the name of that first element?


Solution

  • I did it using children().

    foreach ($xml->children() as $kid) {
        if ($kid->getName() == 'fruit') {
            //do something fruity
        }
    }