Search code examples
phpsimplexml

Get attribute value in SimpleXML object by element and another attribute value


I have such XML :

<root>
    <some_nodes>
    </some_nodes>
    <currencies>
        <currency id="UAH" rate="1.000000"/>
        <currency id="USD" rate="27.000000"/>
        <currency id="RUB" rate="0.380000"/>
        <currency id="EUR" rate="29.350000"/>
    </currencies>
</root>

How can I get rate value where currency id="EUR" with SimpleXML? Is it possible without foreach?


Solution

  • You can use SimpleXML's xpath method to return an attribute of a node based on the value of another attribute:

    $sxml = simplexml_load_string($xml);
    
    $rate = (float) $sxml->xpath('./currencies/currency[@id="EUR"]/@rate')[0];
    
    echo $rate;
    

    Note that the method will always return an array, so we need to ask for the first element, and then cast the value to a float.

    See https://eval.in/957883 for a full example