0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.