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;
You can iterate through simpleXML objects with a
foreach
Just use XPath to get any node with the attribute @currency equal to "USD", that will do the trick.
You are right. Currently you are assuming the
0th
entry to beUSD
and if the order changes in the future your assumption fails. So to make your application independent of the order, you can check for thecurrency
attribute in a loop. The moment you find one with value"USD"
you can get its correspondingrate
attribute.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.
You can use xpath