Tuesday, May 28, 2013

Convert money with google API

This is a small example on how to use the google API to convert euros in any given currency. The parameters are the target currency in a 3 letter code and the float value in euros. If you want to use a different source currency (maybe as a parameter), search for the "EUR" in the URL.
<?php
echo convertMoney("GBP", 3);

function convertMoney($targetCurrency, $price)
{
   if($targetCurrency != "EUR")
   {
      return str_replace(",", ".", 
         _getMoneyFromGoogle($targetCurrency, $price));
   }
   return $price;
}

function _getMoneyFromGoogle($targetCurrency, $price)
{
   $matches = Array();
   $response = file_get_contents(
      "http://www.google.com/ig/calculator?hl=de&q=".
      $price."EUR%3D%3F".$targetCurrency, true);
   preg_match('/rhs:\s*"([^"]+)"/', $response, $matches); 
      //json string is not correctly formated, do it manually
   $result = $matches[1];
   $result = ereg_replace("[^0-9,]*", "", $result); 
      //currency name is still part of string, 
      // remove everything than numbers and comma

   return $result;
}
?>

No comments:

Post a Comment