dougu4704 2017-05-06 08:21
浏览 47
已采纳

谷歌货币转换器api用于大量数据

I am using google finance calculator to convert currency. I have to convert atleast = 2000 numbers to be converted at once. Below I have set only 10 numbers in the array. When I run this code, it is working fine but it is taking too much time. When I try with around 5000 numbers, it sometimes time out error. Can anybody help me how can I modify with my code for large number of datas. Thank you. Below is code that I am currently using.

$amounts= array(10, 20, 30, 40, 50, 60, 70, 80, 90, 100);
$from_Curr ='USD';
$to_Curr = 'THB';
$convertedCurrency = convertCurrency($amounts, $from_Curr, $to_Curr);
print_r($convertedCurrency);

function convertCurrency($amounts= array(), $from, $to){
    $convertedCurrency = array();
    foreach ($amounts as $amount) {
        $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]);
        array_push($convertedCurrency, round($converted, 3));
    }
    return $convertedCurrency;
}
  • 写回答

2条回答 默认 最新

  • doujujian0052 2017-05-06 09:06
    关注

    Let's imagine a request gets anwered in 50ms, you can do the calculation yourself for 5000 requests...

    Change the method of approaching the problem : exchange rates are linear, so you just need one answer, and you can do after the exchange calculation without the API. A multiplication operation is much faster than an API request. Ask the API for the counter value of 1 USD, and then multiply each USD amount by the obtained value :

    $amounts = array(10, 20, 30, 40, 50, 60, 70, 80, 90, 100);
    
    $from_Curr = 'USD';
    $to_Curr = 'THB';
    
    $convertedCurrency = convertCurrency($amounts, $from_Curr, $to_Curr);
    print_r($amounts);
    print_r($convertedCurrency);
    
    function convertCurrency($amounts = array(), $from, $to) {
        $convertedCurrency = array();
        $amount = 1;
    
        $url = "https://finance.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]);
    
        foreach ($amounts as $amount) {
            $convertedCurrency[] = $amount * $converted;
        }
    
        return $convertedCurrency;
    }
    

    Sidenote: changed the regex to a non greedy match (.*?), in case spans are added lataer in the page.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?