Convert currency using Google API calculator

In: PHP

September 07th, 2010.

When there is a need for converting currency, you can use Google calculator API. It is easy to get value, and after you get it – all you have to do is parse it. Copy this simple snippet in order to make currency converter work on your website.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function currency($from_Currency, $to_Currency, $amount) {
	$amount = urlencode($amount);
	$from_Currency = urlencode($from_Currency);
	$to_Currency = urlencode($to_Currency);
 
	$url = "http://www.google.com/ig/calculator?q=$amount$from_Currency=?$to_Currency";
	$ch = curl_init();
	$timeout = 0;
	curl_setopt ($ch, CURLOPT_URL, $url);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	$rawdata = curl_exec($ch);
	curl_close($ch);
 
	$data = explode("’, $rawdata);
	$data = explode(‘ ‘, $data[‘3?]);
	$var = $data[‘0?];
	return round($var,3);
}

Here you can see the raw output for converting 1 USD in EUR: http://www.google.com/ig/calculator?q=1EUR=?USD.

Script was found on Dynamic Guru website, and was improved by SeanJA.

Written by

Dejan is pragmatic software developer with Master's Degree in Computer Science. He is currently based in Belgrade (Serbia).