简体   繁体   English

使用货币转换器以获得更快结果的最佳方法

[英]Best way to use currency converter for faster result

Currency i am using google finance api for converting currencies the code is below 货币我正在使用Google Finance API转换货币,代码如下

 <?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. 一切正常,我正在正确转换,但是现在我面临的问题是在我的网站上会有很多产品,所以我必须使用foreach来迭代所有产品,并在循环中迭代,我称之为货币转换器功能可根据用户所在位置转换价格,但是随着产品的增加,转换所有货币所需的时间也在增加。所以我想知道是否还有其他方法可以进行此转换,以便不会影响我网站的性能。

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. 您只需要一个转换率,以便每个页面加载一次api调用。 let's assume you are converting the price from USD to GNF (I am from Guinea) . 假设您要将价格从USD转换为GNF(我来自几内亚)。 just convert from 1 USD -> ? 只需从1 USD转换->? GNF 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 从现在开始,您可以使用此汇率,将产品价格乘以从api获得的汇率,将所有产品价格从USD转换为GNF

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. 这样,您不必为页面上的每个产品都调用api。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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