PHP simpleXML parsing

时间秒杀一切 提交于 2019-12-12 19:23:09

问题


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;

回答1:


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'];



回答2:


They provide example code at this page:

  • http://www.ecb.europa.eu/stats/exchange/eurofxref/html/index.en.html

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.




回答3:


You can iterate through simpleXML objects with a foreach

foreach( $xml->Cube->Cube as $cube ) {
    if( isset( $cube->attributes()->rate ) ) {
         $rate = $cube->attributes()->rate; 
    }    
}



回答4:


You can use xpath

$rate = $xml->xpath("//Cube[currency='USD']/rate")



回答5:


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.



来源:https://stackoverflow.com/questions/2461757/php-simplexml-parsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!