Free PHP Currency Conversion

Published:
Updated:
I spent quite a while recently looking for a way to convert currency online. I thought, "There must be a free currency conversion API or XML or something!" But all I found for over an hour was silly solutions that either cost $60 a month or didn't do what I wanted. All I wanted was a simple XML file that would tell me the current exchange rates. Guess what, THERE IS ONE! And here it is:

http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml

This is the official exchange rate document published in XML format by the European Central Bank free for public consumption :) It gives all the reference rates in comparison to the Euro, so you just have to find what you want and do a little math. All you have to do is load this document into your favorite XML parser, and read the elements you need! I used PHP to get the exchange, which looked something like this:

 
function getRateFor($currency) { 
                      	//Load the reference rates published by the European Central Bank
                      	$sXML = simplexml_load_file("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
                       	//Find the currency rates we want
                      	foreach($sXML->Cube->Cube->Cube as $rate)
                      	{
                      		if((string) $rate['currency'] == "USD") $USD = (string) $rate['rate'];
                      		if((string) $rate['currency'] == $currency) $CUR = (string) $rate['rate'];
                      	}
                       	
                      	return $CUR/$USD;
                      }  
                      //Use Example:
                      $PriceInDollars = 100;
                      $PriceInPounds = getRateFor("GBP")*$PriceInDollars
                      

Open in new window


Of course I've removed a bit of error checking for simplification :)
1
2,822 Views

Comments (1)

David BeveridgeLinux Systems Admin
CERTIFIED EXPERT

Commented:
Here is another one
http://www.bankofcanada.ca/stats/assets/csv/fx-seven-day.csv
http://www.bankofcanada.ca/stats/assets/xml/noon-five-day.xml

I found it was a good idea to run a daily cron job to download the table into a local sql database.
That way my website is not impacted by any delays or outages at the upstream.

see
http://www.bankofcanada.ca/rates/exchange/noon-rates-5-day/ 
for more details and Terms & Conditions.

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.