Long, long time ago, in a galaxy far, far away
I was searching for a way to get the exchange rate automatically and use it in a project I was working on back then. And, following the will of the Force, I’ve came up with this script, which queries Google for the exchange rate and parses the answer page with regular expressions.
The script has proven useful to a lot of people, but, several days ago, an user called Lars Sorhus posted a comment in which he posted a link to another Google service, that outputs a (malformed) JSON containing the exchange rate.
The JSON based solution is much more elegant than parsing a HTML file with regular expressions, so I went for it, but since Google’s conversion service doesn’t output well formatted json, PHP’s built-in json_decode() function won’t work, so I had to look for another parser.
I’ve settled for PEAR’s Services_JSON class for decoding the JSON, as the test said that it can parse almost anything. And it does. Here’s is an working example:
/**
* queries Google for the current exchange rate, doesn't need cURL
*
* @param mixed $amount
* @param string $currency
* @param string $exchangeIn
* @throws Exception
* @return mixed
*/
function exchangeRate($amount, $currency, $exchangeIn) {
$url = @ 'http://www.google.com/ig/calculator?hl=en&q=' . urlEncode($amount . $currency . '=?' . $exchangeIn);
$data = @ file_get_contents($url);
if(!$data) {
throw new Exception('Could not connect');
}
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$array = $json->decode($data);
if(!$array) {
throw new Exception('Could not parse the JSON');
}
if($array['error']) {
throw new Exception('Google reported an error: ' . $array['error']);
}
return (float) $array['rhs'];
}
It uses exception, because I think that the OOP exceptions based approach is much better than return false or adding a passed by reference parameter to be used for error signaling. It’s very simple to use:
try {
$rate = exchangeRate(1, 'euro', 'usd');
echo 'Exchange rate is: ' . $rate;
}
catch(Exception $exception) {
// log $exception->getMessage()
echo 'Due to technical difficulties, we couldn\'t get the exchange rate';
}
Of course, you must include the Services_JSON.php class from the PEAR repository prior to calling exchangeRate().