Google provides a simple and free* API for querying currency exchange rate. You can convert the currency using google apis url which are given below
https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency
Where a is the amount .We can do this by two methods which are given below.
1 By using file_get_contents
function currency($fromCur,$toCur,$amount) {
$amount = urlencode($amount);
$fromCur = urlencode($fromCur);
$toCur= urlencode($toCur);
$get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$fromCur&to=$toCur");
$get = explode("<span class=bld>",$get);
$get = explode("</span>",$get[1]);
$convertedamount = preg_replace("/[^0-9\.]/", null, $get[0]);
return round($convertedamount,2000);
}
echo currency("USD","INR",2000);
2 By using the curl method
function currency($fromCurrency, $toCurrency, $amount) {
$url = "https://www.google.com/finance/converter?a=" . $amount . "&from=" . $fromCurrency . "&to=" . $toCurrency;
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$rawdata = curl_exec($ch);
curl_close($ch);
$matches = array();
preg_match_all("|<span class=bld>(.*)</span>|U", $rawdata, $matches);
$result = explode(" ", $matches[1][0]);
return round($result[0], 2);
}
$usd = currency("USD", "ETB", 2000);
echo "2000 USD = " . $usd . " ETB";
By these ways we will get the raw data which requires regular expression for the conversion result.
0 Comment(s)