How to convert currencies using cURl and Google + PHP

February 7, 2012 | Miscellaneous, Web Development

Advertisement currency

Converting currency would not have been a big deal if the exchange rate was fixed. But given that the exchange rate changes every other second, we use services from one of the trusted sites to show  the latest exchange rates. Here we take help of Google to find the latest currency exchange rate and convert the currency to required currency. I hope this piece of code helps you.

function convert_currency($from,$to,$amount) {
$amount = urlencode($amount);
$from = urlencode($from);
$to = urlencode($to);
$url = “$amount$from=?$to”;
$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);
$data = explode(‘”‘, $rawdata);
$data = explode(‘ ‘, $data[‘3′]);
$var = $data[‘0′];
return round($var,2);

All you have to do now is call the function on your file and at required place and pass the To and From Currency and the amount to be converted.  Like you would call a regular function.

<?php convert_currency(“USD”,”GBP”,”500″); ?>

That is it. a no nonsense snippet of code to get the job done.

Author Information
Utsav Singh Rathour
Utsav Singh Rathour is a blogger and developer for over 5 years and believes in building applications that not only tackles the problem but gives users a better interface. He is founder of Code Pixelz Media and blogs mainly at this place. Follow him at @rathour

Leave a Reply

WP Engine 15% off with NEWYEARNEWHOSTING15

  • Like what you see?

    We put a lot of effort to bring you best content. Please donate to help us survive.

  • Like us on Facebook

  • Tags