简体   繁体   中英

Best way to use currency converter for faster result

Currency i am using google finance api for converting currencies the code is below

 <?php
      function convertCurrency($amount, $from, $to){
        $url  = "https://www.google.com/finance/converter?a=$amount&from=$from&to=$to";
        $data = file_get_contents($url);
        preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
        $converted = preg_replace("/[^0-9.]/", "", $converted[1]);
        return round($converted, 3);
      }

      # Call function  
      echo convertCurrency(1, "USD", "INR");
      ?>

everything is working fine i am getting the correct conversion but now the problem i am facing is that on my website lot of products gonna be there so i have to use foreach for iterating through all the products and while iterating through the loop i am calling the currency converter function to convert the price based on user location but as the product is increasing so the time it tooks to convert all currency is also increasing.So just wanna know is there any other way through which i can do this conversion so that it don't effect the performance of my site.

First of all as a starting point do not try convert all the price every time. You just need a conversion rate so one api call per page load. let's assume you are converting the price from USD to GNF (I am from Guinea) . just convert from 1 USD -> ? GNF

$UsdToGnfRate=convertCurrency(1, 'USD', 'GNF')

from now on you can use this rate to convert all your product prices from USD to GNF by multipliying the product price by the rate you got from the api

foreach($products as $item){
  $localPrice=$item['price'] * $UsdToGnfRate
}

You can make some test and see for your self or look for currency conversion which is based on the rate. This way you don't call the api for every product on your page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM