How to convert currencies using cURl and Google + PHP

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.

Leave a Reply