views:

229

answers:

5

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;
A: 

You can iterate through simpleXML objects with a foreach

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

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.

Gordon
+2  A: 

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'];
Josh Davis
A: 

You can use xpath

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

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.

codaddict