php - 适用于大量数据的 Google 货币转换器 api

标签 php

我正在使用 Google 金融计算器来换算货币。我必须一次至少转换 2000 个要转换的数字。下面我只在数组中设置了 10 个数字。当我运行这段代码时,它工作正常,但花费了太多时间。当我尝试使用大约 5000 个数字时,有时会出现超时错误。任何人都可以帮助我如何修改我的代码以处理大量数据。谢谢。下面是我当前正在使用的代码。

$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;
}

最佳答案

假设一个请求在 50 毫秒内得到答复,您可以自己计算 5000 个请求...

改变解决问题的方法:汇率是线性的,所以你只需要一个答案,不需要API就可以在汇率计算之后进行。乘法运算比 API 请求快得多。向 API 请求 1 美元的计数器值,然后将每美元金额乘以获得的值:

$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;
}

旁注:将正则表达式更改为非贪婪匹配 (.*?),以防在页面中稍后添加跨度。

关于php - 适用于大量数据的 Google 货币转换器 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43818304/

相关文章:

php - 使用 javascript 访问 php 文件中的 session 变量?

php - 如何使用 OR 条件从 cakephp 3.0 中的 mysql 表中获取记录?

php - Laravel 模型的多列 "pivot"表查询

php - 需要帮助将 php curl 代码转换为 C 语言

javascript - 为什么我收到对象对象错误?

php - 如何在路由中为多个参数实现 "defaults()"- Laravel

php - SQL join into join 创建好数组

php - Slim 4错误处理未捕获基本异常

javascript - 如何将条件 PHP if 短语更改为 JS?

javascript - jQuery <select> 选项仅启用一些选项