<

Free PHP Currency Conversion

Published on
5,520 Points
2,420 Views
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:

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
Comment
Author:mltsy
1 Comment
 
LVL 19

Expert Comment

by:bevhost
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.
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Join & Write a Comment

The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month