How to get the Currency Rate from Third Party API

How to get the Currency Rate from Third Party API?

This Small  function is used to call the API & get the currency Conversion Rate.

By using this  you can get easily the conversion rate.

$fromCurrency = "USD";
$toCurrency   = "INR";


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) {
        $conversion_rate = 0;
   }

}


# Now, Show the Result::

print_r($conversion_rate);

 

Leave a Comment