合并多个大型API响应的最佳方法

时间:2018-07-17 07:48:19

标签: php rest api merge response

我正在尝试通过REST API(基于文档https://www.smtpeter.com/en/documentation/rest-logfiles上的文件)从基于云的SMTP服务器获取日志文件。

API仅允许我请求1天的日志文件(例如https://www.smtpeter.com/v1/logfiles/deliveries.2018-07-17.log/json)。 1天的日志文件包含大约10.000条记录。但是,我想要一个星期甚至一个月的日志文件。我已与公司联系,询问他们是否支持API请求超过1天,但不支持。他们说我应该提出多个请求,然后自己合并响应。

我的编程知识有限,而我使用API​​的知识基本上为零。但是在Google的帮助下(以及许多其他的SO问题),我想到了以下PHP脚本:

<?php
// Disable time limits
set_time_limit(0);

// Let's set some variables
$api_key = '###';
$date=date_create("2018-04-02");
$days = [];

for($i = 0; $i <=6; $i++) {
    // Variables
    $deliveries_url = 
    'https://www.smtpeter.com/v1/logfiles/deliveries.'.date_format($date,"Y-m-d").'.log/json/?access_token='.$api_key;

    // Make an array for this day/iteration and put the API response inside the array  
    ${"day$i"} = json_decode(file_get_contents($deliveries_url), true);

    // Add array name to the days array in order to know how many days we need to merge later
    array_push($days,${"day$i"});

    // Add 1 day before starting all over again    
    date_add($date,date_interval_create_from_date_string("1 days"));
}

// Merge all data that we've previously gathered
$data = call_user_func_array('array_merge', $days);
?>

因此,这将每次以不同的日期发出多个请求,并将解码后的JSON放入数组中。循环完成后,它将所有数组合并为1个大数组。它实际上可以正常工作2天(大约20.000条记录)。但是,当我将循环最多推进3天,4天或更长时间时,我将得到一个空数组(猜测它正在超时或其他原因)。

我猜想这可能是实现目标的最无效的方法。所以请提出建议:达到我的目标的最佳方法是什么?

0 个答案:

没有答案