我有一个获取文件并将其返回给用户的网络服务(基于 Symfony)。自从我使用 curl 来做到这一点。
我刚刚找到 guzzlehttp,它看起来很棒。但是,我不知道如何在不将下载的文件(xml 或 txt)保存到本地文件的情况下使用 guzzle 执行此操作,从文件系统中读取它并将其返回给用户。我想这样做而不保存到文件系统。
public function streamAction()
{
$response = $client->request(
'GET', 'http://httpbin.org/stream-bytes/1024', ['stream' => true]
);
$body = $response->getBody();
$response = new StreamedResponse(function() use ($body) {
while (!$body->eof()) {
echo $body->read(1024);
}
});
$response->headers->set('Content-Type', 'text/xml');
return $response;
}
$response = $client->request('GET', 'http://example.com/file', ['stream' => true]);
$stream = $response->getBody();
$content = new StreamedResponse(function () use ($stream) {
/** @var StreamInterface $stream */
while ($binary = $stream->read(1024)) {
echo $binary;
ob_flush();
flush();
}
}, $response->getStatusCode(), [
'Content-Type' => $response->getHeaderLine('Content-Type'),
'Content-Length' => $response->getHeaderLine('Content-Length'),
'Content-Disposition' => $response->getHeaderLine('Content-Disposition')
]);
return $this->renderResponse($content->send());