Search code examples
phpxmlsimplexml

How can i compare the values of the attributes on XML and only echo the attribute that contains the string i want with PHP?


So this is an example on how my XML looks like (I use SimpleXML and i would like to keep that way.).

<foo>
  <foo1>
    <energy A="false" B="false" C="false" D="true" E="false" F="false"/>
  </foo1>
</foo>

This is my PHP so far:

$energyR = $xml->foo->foo1->energy[0]->attributes();
foreach($energy as $key => $ener){
 echo $key, $ener;
}

The result is the following:

AfalseBfalseCfalseDtrueEfalseFfalse

Now what i want: To iterate through all the attributes and find which one is true and save ONLY the attribute that is true, to a variable.

That means that the result should be:

D (because this is the one which has the value of true)

Any ideas? A complete new code is acceptable too. As i mentioned, i use SimpleXML so please your answers only when it comes to SimpleXML.


Solution

  •    foreach($energy as $key => $ener){
            if ($ener == 'true') {
                echo $key;
            }
        }
    

    like this