我写了一个 PHP 脚本,它使用 HTTP POST 请求curl并执行以下操作,
这是代码:
$ch = curl_init ( $url );
curl_setopt ( $ch, CURLOPT_COOKIE, "cookie=cookie");
curl_setopt ( $ch, CURLOPT_POST, 1);
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ( $ch, CURLOPT_HEADER, 0);
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
// this point
extr ( $response, $param_1, $param_2);
Run Code Online (Sandbox Code Playgroud)
问题是,有时响应大于 1GB,所以 PHP 代码暂停,直到接收到完整响应(如代码所示// this point),如果接收到格式错误的 HTML,PHP 会产生错误,所以这里所有的事情都需要从头开始.
下面是其余的功能:
function extr($string = '',$a,$b)
{
$doc = new DOMDocument;
@$doc -> loadHTML($string);
$table = $doc -> getElementById('myTableId');
if(is_object($table)):
foreach ($table->getElementsByTagName('tr') as $record)
{
$rec = array();
foreach ($record->getElementsByTagName('td') as $data)
{
$rec[] = $data -> nodeValue;
}
if ($rec)
{
put_data($rec);
}
}
else:
{
echo 'Skipped: Param1:'.$a.'-- Param2: '.$b.'<br>';
}
endif;
}
function put_data($one = array())
{
$one = json_encode($one) . "\n";
file_put_contents("data.json", $one, FILE_APPEND);
}
ini_set('max_execution_time', 3000000);
ini_set('memory_limit', '-1');
Run Code Online (Sandbox Code Playgroud)
我能想到的替代方法是处理接收到的数据,如果可能,使用 curl,或从先前状态继续先前的 curl 请求。
有没有可能的解决方法?
为此,我是否需要切换到 PHP 以外的任何其他语言?
您可以使用CURLOPT_WRITEFUNCTION带有回调的选项来分块处理数据:
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function(&$ch, $data) {
echo "\n\nchunk received:\n", $data; // process your chunk here
return strlen($data); // returning non-positive number aborts further transfer
});
Run Code Online (Sandbox Code Playgroud)
正如评论中已经提到的那样,如果您的响应内容类型是您加载到 DOMDocument 中的 HTML,那么无论如何您首先需要完整的数据。