我正在通过第三方 API 加载视频。
它返回正文中的二进制文件以及标题Transfer-Encoding :chunked。
我正在使用Guzzle 4api,如何轻松地将其传输到浏览器,这样我就不需要先将整个内容加载到 PHP 内存中?
我不想将其设置为attachment,因为我希望它在浏览器中播放而不是下载。
<?php
$client = new GuzzleHttp\Client();
// Download the video and stream it to the client
$response = $client->get($url)->send();
//But this will have to cache the whole thing in PHP memory first...
header("Content-Type:{$response->getHeader('Content-Type')}");
echo $response->getBody();
Run Code Online (Sandbox Code Playgroud)
如果还有人在看这个...
默认情况下,Guzzle 4 响应不是流(它们是最新版本),您必须在请求选项中启用它。
['stream'=>true]
Run Code Online (Sandbox Code Playgroud)
然后使用Streamutil 读取流的每一行..
GuzzleHttp\Stream\Utils::readline
Run Code Online (Sandbox Code Playgroud)
所以....
<?php
$client = new GuzzleHttp\Client();
// Download the video as a stream
$response = $client->request('GET', $url, ['stream'=>true])->send();
//$body is now a Guzzle stream object.
$body = $response->getBody();
header("Content-Type:{$response->getHeader('Content-Type')}");
while (!$body->eof()) {
echo GuzzleHttp\Stream\Utils::readline($body);
ob_flush();
flush();
}
Run Code Online (Sandbox Code Playgroud)