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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器