Jens Barfred
Jens Barfred

Reputation: 1

How to get attribute value from element with several attributes

I have this xml file (part of it):

<exchangerates xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" type="Valutakurser" author="Danmarks Nationalbank" refcur="DKK" refamt="1">
<dailyrates id="2020-10-23">
<currency code="AUD" desc="Australske dollar" rate="448,83"/>
<currency code="BGN" desc="Bulgarske lev" rate="380,44"/>

I want to get the rate from AUD, Australian dollar.

My xpath query looks like this:

$result = $xml->xpath("/exchangerates/dailyrates/currency[@code = 'AUD']");

It works and deliver this output:

Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [code] => AUD [desc] => Australske 
    dollar [rate] => 448,83 ) ) )

And now I am stuck. I want the [rate] value. But how? I have solved this in c# using a navigator. But now I am using php. I could use javascript if necessary.

Upvotes: 0

Views: 39

Answers (1)

theBittor
theBittor

Reputation: 834

From the xpath point of view, you just need to add /@attributeName to your xpath.

/exchangerates/dailyrates/currency[@code = 'AUD']/@rate

Upvotes: 1

Related Questions