PHP simpleXML parsing

2019-07-19 22:59发布

问题:

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.