Skip to content

Instantly share code, notes, and snippets.

@morgant
Forked from SeanJA/google_convert_currency.php
Created February 26, 2011 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save morgant/844906 to your computer and use it in GitHub Desktop.
Save morgant/844906 to your computer and use it in GitHub Desktop.
Caching currency conversion using Google Calculator.
<?php
$currencyCache = array();
/**
* Looks for unquoted keys in a json string and fixes them ie: {a:"b"} => {"a":"b"}
* @param string $string A json string that is suspect
* @return string A valid json string
*/
function fix_json($string){
// (no qupte) (word) (no quote) (semicolon)
$regex = '/(?<!")([a-zA-Z0-9_]+)(?!")(?=:)/i';
return preg_replace($regex, '"$1"', $string);
}
/**
* Change one currency into another using google's currency calculator
* @param string $fromCurrency The currency you are starting with
* @param string $toCurrency The currency you want to calculate
* @param float $amount The amount of money you want to check
* @return float The amount in a new currency
*/
function currency($fromCurrency,$toCurrency,$amount) {
global $currencyCache;
$key = $fromCurrency.'-'.$toCurrency;
if ( !array_key_exists($key, $currencyCache) ) {
$amount = urlencode($amount);
$fromCurrency = urlencode($fromCurrency);
$toCurrency = urlencode($toCurrency);
$url = 'http://www.google.com/ig/calculator?hl=en&q=1' . $fromCurrency . '=?' . $toCurrency;
$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);
//since google is returning invalid json, add the quotes back in
$data = fix_json($rawdata);
$data = json_decode($data, true);
$currencyCache[$key] = $data['rhs'];
}
return round($amount * $currencyCache[$key], 2);
}
/* Example usage: echo currency('USD', 'GBP', 100); */
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment