<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Free PHP Currency Conversion

Published on
5,583 Points
2,483 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

OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Join & Write a Comment

The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month