设置 Guzzle 检索的最大内容量

Set the maximum amount of content to be retrieved by Guzzle

我想下载给定 URL 的前 16 KB,为此我正在使用 GuzzleHTTP 库。检查 Content-Length header 或发送 Ranges header 将无法满足我的目的,因为服务器可能不会 send/accept 任何这些 header s.

有没有办法设置 Guzzle 应检索的最大内容量?

是的,有办法。使用 stream option 分块下载内容,而不是一次全部下载。

$response = $client->request('GET', '/stream/20', ['stream' => true]);
// Read bytes off of the stream until the end of the stream is reached
$body = $response->getBody();
$buffer = '';
while (!$body->eof() && (strlen($buffer) < 16384)) {
    $buffer .= $body->read(1024);
}
$body->close();

使用此解决方案,您可以控制要下载的内容量。