How to get the Currency Conversion Rate in php

How to get the Currency Conversion Rate in php?

Here, the function is used to get the currency conversion rate,

To get the currency conversion rate , just call the function with the parameters.
Like:
$rate = $this->CurrencyRate(‘USD’, ‘INR’);
// To get the Currency Rate from Third Party API

public function currencyRate($fromCurrency, $toCurrency)
{
    $conversion_rate = 0;

    if (!empty($fromCurrency) && !empty($toCurrency) )
    {

       $currencyString = strtoupper($fromCurrency.'_'.$toCurrency);  

       $fetchUrl = 'http://free.currencyconverterapi.com/api/v5/convert?q='.$currencyString.'&compact=y';

 
       try 
       {

          $handle_contents =  file_get_contents($fetchUrl);

          $contentsDecoded= @json_decode($handle_contents, TRUE);

          if(!empty($contentsDecoded[$currencyString])){

             $curData = $contentsDecoded[$currencyString];

             if(!empty($curData['val'])){

                $conversion_rate = floatval($curData['val']);
             }

          }
       } 
       catch (Exception $e) 
       {
       }
   }

    return($conversion_rate);

}

// function Ends

To get the currency conversion rate , just call the function with the parameters.
Like:
$rate = $this->CurrencyRate('USD', 'INR');

1 thought on “How to get the Currency Conversion Rate in php”

Leave a Reply

Your email address will not be published. Required fields are marked *