Currency Conversion With Google Calculator

Working on a recent project I found myself in the market for a way to simply calculate what one currency is worth in relation to another. After some looking around I was surprised to find currency conversion can be performed quickly and simply using the Google Calculator API. To use you need only make a request to the API similar to this:

http://www.google.com/ig/calculator?hl=en&q=1AUD=?USD

Simply substitute the currency quantity and code on the left hand side of the query. With the currency code you would like to convert the number into on the right hand side of the query. The API will the respond with the result of the coversion with a response similar to below:

{lhs: “1 Australian dollar”,rhs: “1.0218 U.S. dollars”,error: “”,icc: true}

Putting it all together with an example using PHP & CURL

[codesyntax lang=”php”]

/**
* For a list of possible country codes take a look at http://en.wikipedia.org/wiki/Currency_code#Active_codes
**/
Currency Conversion With Google CalculatorCurrency Conversion With Google CalculatorCurrency Conversion With Google CalculatorCurrency Conversion With Google Calculator
// Currency code for the currency we are converting.
$fromCurrency = 'AUD';

// Currency code that we would like to covert into
$toCurrency = 'CAD';

// Call the function and convert the chosen currency
echo convertCurrency($fromCurrency, $toCurrency);Currency Conversion With Google Calculator

/** Start currency conversion function **/

function convertCurrency($fromCurrency, $toCurrency, $currencyAmount = NULL) 
{
		if (!$currencyAmount) {
			$currencyAmount = 1;
		} 
		$apiRequest = 'http://www.google.com/ig/calculator?hl=en&q=' . $currencyAmount . $fromCurrency . '=?' . $toCurrency;

		$ch = curl_init($apiRequest);	 	
                curl_setopt($ch, CURLOPT_VERBOSE, 1);
                curl_setopt($ch, CURLOPT_NOBODY, 0);Currency Conversion With Google Calculator
                curl_setopt($ch, CURLOPT_HEADER, 0);Currency Conversion With Google Calculator
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

		$apiResponse = curl_exec($ch);
		$responseInformation = curl_getinfo($ch);
		curl_close($ch);

		if($responseInformation['http_code'] === 200 ) {
			$apiResponse = explode(',', preg_replace('/([^0-9.,]+)/', '', $apiResponse));
			return substr_replace($apiResponse[1], '', -2);
		}	
}
/** End currency conversion function **/

[/codesyntax]

Leave a Reply

Your email address will not be published. Required fields are marked *