Free PHP Currency Conversion

Published on
5,674 Points
1 Endorsement
Last Modified:
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("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 :)
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Get 7 days free