Reputation: 125
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?
Upvotes: 0
Views: 1434
Reputation: 17417
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
Upvotes: 2