将PSR-7流写入文件

时间:2019-04-01 09:56:51

标签: php stream psr-7

我正在建立一个透视图像缓存,我正在寻找一种将PSR-7流写入服务器上文件的方法。该文档对如何执行此操作并不十分清楚(它主要侧重于提供文件,而不是编写文件)。

我目前的最大努力是使用$stream->detach(),这并不理想(因为它破坏了基础流,因此我无法返回给用户)。有更好的方法吗?

/* @var GuzzleHttp\Client $httpClient */
$response = $httpClient->request(
  'GET', 'https://example.com/image.png'
);

// Validate response, etc.

$stream = $response->getBody();

$stream->isReadable(); // now true

$cachePath = '/path/to/local/cache/unique-name.png';

$writeHandle = fopen($cachePath, 'w');
stream_copy_to_stream($stream->detach(), $writeHandle);

$stream->isReadable(); // now false due to detach()

// To serve the data I'd need to create a new stream 
// from the image I've just created
return new GuzzleHttp\Psr7\Stream(fopen($cachePath, 'rb'))

抢先解决所有“为什么要这么做”的问题;我从远程服务获取这些图像。该服务的条款要求我在本地缓存图像。

0 个答案:

没有答案
相关问题