FFish FFish - 2 months ago 18
PHP Question

PHP simpleXML parsing

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;

Answer

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