文件的cURL响应部分-大JSON文件-PHP


cURL response parts of file - big JSON file - PHP

我正试图将大量数据从服务器cURL到门户网站。数据是一个JSON,包含大约1000篇文章的数据。显然,数据太大了,无法一次性获取。

我试图增加所有参数以增加超时限制,但它不起作用:

set_time_limit(0);
ini_set('memory_limit','1024M');
ini_set('max_execution_time', 1200);

我的PHP代码:

$oJsonResponse = json_decode(call_API(json_encode($oJsonMessage)));
function call_API($data)
{
    $API_URL = "~some url~";
    $ch = curl_init($API_URL);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'data='.$data);
    $return = curl_exec($ch);
    return $return;
}

我想尝试的是分部分发送我的cURL请求的响应。有可能吗?


PS:我使用数据表来显示数据,如果我能显示第一部分并在得到它时加载其余部分,那将是非常棒的,但我想PHP不是这样的语言?

您需要从远程服务器逐段获取数据。请查看以下建议的代码。

$page = 0;
$resp = true;
while ($resp) {
    $page++;
    $resp = call_API(json_encode($oJsonMessage), $page);
    //consume your data
    if ($resp) {
        $data = json_decode($resp);
    }
}
function call_API($data, $page) {
    $API_URL = "~some url~";
    $ch = curl_init($API_URL);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'data=' . $data . '&page=' . $page);
    $return = curl_exec($ch);
    //Test for end of result here before returning a value
    return empty($return) ? false : $return;
}

从理论上讲,远程服务器上的代码看起来是这样的。

$data = $_POST['data'];
$page = $_POST['page'];
$itemsPerPage = 200;
$offset = ($page - 1) * $itemsPerPage + 1;
$resp = $db->getFunction($data, $offset, $itemsPerPage);
echo $resp ? json_encode($resp) : '';