For a project I’m working, I needed to get shipping rates from the UPS API (a blog post about this will follow soon).
The problem I ran into was that the UPS API returns the shipping rates with the currency of the country where the rates for are asked, so you can’t force it to always return the rates in EUR.
One solution to convert the prices is to make a very big array with all currency rates in it. I then would maintain the array every day at 9’o clock to check if the rates weren’t changed. Right, that’s not an option.
Like you might know you can easily convert currencies by using the Google search engine. For example searching on “1 Euro to dollar” will retrieve the Euro in dollar.
Below the class I wrote to convert currencies using the Google currency converter.
sConvertorUrl, $this->fPrice, $this->sFrom, $this->sTo);
$sResponse = file_get_contents($sUrl);
if(!$sResponse) {
throw new Exception('Google currency convertor is not available at the moment');
}
$oResult = json_decode($sResponse);
if($oResult->error != '') {
throw new Exception('The following error occurred: '.$oResult->error);
}
// Isolate the price
return (float)$oResult->rhs;
}
/**
* Get, retrieve the foreign currency
*
* @param float $fPrice
* @param string $sFrom, currency code (EUR, USD,...)
* @param string $sTo, currency code (EUR, USD,...)
*/
public function get($fPrice, $sFrom, $sTo)
{
if(!is_float($fPrice)) {
throw new Exception('The price to convert should be a float, "'.gettype($fPrice). '" given while calling: '.__FUNCTION__);
}
$this->fPrice = $fPrice;
$this->sFrom = strtoupper($sFrom);
$this->sTo = strtoupper($sTo);
return $this->exec();
}
}
?>
Pretty straightforward as you see.