Free PHP Currency Conversion

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:

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("");
                       	//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 :)

Comments (1)

David BeveridgeLinux Systems Admin

Here is another one

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.

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.