Create a currency converter in php using google finance currency api

In this tutorial I am going to develop a currency converter with the help of Google Finance Currency API. You can use below currency converter function in your project to get updated currency values and convert into other countries value.

There are lots of API available to convert currency, but here i am using Google Finance Currency Converter api . There are basically 3 parameter required: From Currency, To Currency and Amount. Using these three parameter i will send HTTP request on “Google Finance Currency Converter” using file_get_contents and in response you’ll get raw data in HTML format. In the final stage you need to parse html data and get the converted amount.
Here is the function.

function calculateCurrency($from,$to,$amount){
    $url = "".$from.$to;
    $request = curl_init();
    $timeOut = 0;
    curl_setopt ($request, CURLOPT_URL, $url);
    curl_setopt ($request, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($request, CURLOPT_USERAGENT,"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
    curl_setopt ($request, CURLOPT_CONNECTTIMEOUT, $timeOut);
    $response = curl_exec($request);
    preg_match('~<span [^>]* id="knowledge-currency__tgt-amount"[^>]*>(.*?)</span>~si', $response, $finalData);
    return floatval((floatval(preg_replace("/[^-0-9\.]/","", $finalData[1]))/100) * $amount);

Call above function with given parameters

echo calculateCurrency('USD','INR',1);

I have created online currency converter demo using above function.



Other Method

These is another library which you can use to convert currency form one country to another.
Step.1: Download library form here
Step.2: Exchange rates/Currency Converter Library with features of caching and identifying currency from country code.
Use following function after include currency converter library.

require 'vendor/autoload.php';
$converter = new CurrencyConverter\CurrencyConverter;
echo $converter->convert('USD', 'NPR'); // will print something like 97.44
// caching currency
$cacheAdapter = new CurrencyConverter\Cache\Adapter\FileSystem(__DIR__ . '/cache/');
$cacheAdapter->setCacheTimeout(DateInterval::createFromDateString('10 second'));
echo $converter->convert('USD', 'NPR');

If you like this post please don’t forget to subscribe my public notebook for more useful stuff