Quantcast
Viewing all articles
Browse latest Browse all 15

Google currency conversion in PHP

So I was recently faced with billing a client in South African Rand for his Google mailboxes. Since the price would obviously change from month to month based on the current ZAR (South African Rand) to the US Dollar, I had to find a way to talk to my billing API based on the current exchange rate.

After a bit of reading and searching I found the gem on stackoverflow.com by someone called Christophe Herreman. I slightly modified it to be a proper function.


<?php

function currencyConvert($fromCurrency,$toCurrency,$amount){	

  $amount = urlencode($amount);
  $fromCurrency = urlencode($fromCurrency);
  $toCurrency = urlencode($toCurrency);
  $get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$fromCurrency&to=$toCurrency");
  $get = explode("<span class=bld>",$get);
  $get = explode("</span>",$get[1]);  
  $converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);

  return number_format($converted_amount, 2);

}

$amount = "550";
$fromCurrency = 'ZAR';
$toCurrency = 'USD';

echo $amount. ' ' . $fromCurrency . ' makes '. currencyConvert($fromCurrency, $toCurrency, $amount) . ' ' . $toCurrency;
?>

Viewing all articles
Browse latest Browse all 15

Trending Articles