PHP simpleXML parsing

2019-07-19 22:28发布

I need currency conversion, euro to dollar.
The European Central bank provides the rates here:
http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
I can get the USD rate by using the first node, but what if they change the order?
Do I need something more reliable? I have no idea how..

$xml = @simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
echo "dollar: " . $xml->Cube->Cube->Cube[0]->attributes()->rate;

5条回答
放我归山
2楼-- · 2019-07-19 23:14

You can iterate through simpleXML objects with a foreach

foreach( $xml->Cube->Cube as $cube ) {
    if( isset( $cube->attributes()->rate ) ) {
         $rate = $cube->attributes()->rate; 
    }    
}
查看更多
何必那么认真
3楼-- · 2019-07-19 23:19

Just use XPath to get any node with the attribute @currency equal to "USD", that will do the trick.

$xref  = simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
$nodes = $xref->xpath('//*[@currency="USD"]');

echo $nodes[0]['rate'];
查看更多
混吃等死
4楼-- · 2019-07-19 23:21

You are right. Currently you are assuming the 0th entry to be USD and if the order changes in the future your assumption fails. So to make your application independent of the order, you can check for the currency attribute in a loop. The moment you find one with value "USD" you can get its corresponding rate attribute.

查看更多
劳资没心,怎么记你
5楼-- · 2019-07-19 23:22

They provide example code at this page:

Just click the tab For Developers

There is also an (unmaintained) PEAR Package for Exchange Rates

You should not bother if they change the order. If they do, they do.

查看更多
Bombasti
6楼-- · 2019-07-19 23:27

You can use xpath

$rate = $xml->xpath("//Cube[currency='USD']/rate")
查看更多
登录 后发表回答