Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fix json
<?php
/**
* 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) {
$amount = urlencode($amount);
$fromCurrency = urlencode($fromCurrency);
$toCurrency = urlencode($toCurrency);
$url = 'http://www.google.com/ig/calculator?hl=en&q='.$amount . $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);
return round($data['rhs'], 2);
}
echo currency('USD', 'GBP', 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.