user1682701
user1682701

Reputation: 25

Loop through element and attribute of SimpleXmlElement in Php

<info id="12AB" conf="D4XD">
<cinfo code="CB">Consumer Business</cinfo>
<cinfo code="EB">Enterprise Business</cinfo>
</info>

How do I loop through the cinfo elements, that I can read value, i.e. Consumer Business and attribute value, i.e. CB ?

$obj = new SimpleXMLElement($xmldata);
    foreach ($obj->children() as $cinfos) {
?????



    }

Upvotes: 0

Views: 109

Answers (1)

Kostis
Kostis

Reputation: 1105

This should do it:

$obj = new SimpleXMLElement($xml);

foreach ($obj->cinfo as $cinfos) {
    // This is the value
    $val = $cinfos[0];
    echo $val."\r\n";;
    // Iterate through the attributes
    foreach($cinfos[0]->attributes() as $key => $val) {
        echo $key,'="',$val,"\"\n";
    }
}

Upvotes: 1

Related Questions