IT序号网

php之Guzzle 6下载文件

lhb25 2025年01月19日 编程语言 13 0

需要使用Guzzle 6从rest API下载文件的帮助。我不希望将文件保存在本地,而是从Web浏览器下载。到目前为止,下面的代码,但是相信我缺少什么?

    <?php 
 
//code for Guzzle etc removed 
 
$responsesfile = $client->request('GET', 'documents/1234/content',  
        [ 
        'headers' => [ 
            'Cache-Control' => 'no-cache',  
            'Content-Type' => 'application/pdf', 
            'Content-Type' => 'Content-Disposition: attachment; filename="test"' 
        ] 
        ] 
 
 
    ); 
    return $responsesfile; 
    ?> 

请您参考如下方法:

只需在Guzzle的文档中进行研究,例如here

传递字符串以指定将存储响应正文内容的文件的路径:

$client->request('GET', '/stream/20', ['sink' => '/path/to/file']); 

传递从fopen()返回的资源以将响应写入PHP流:

$resource = fopen('/path/to/file', 'w'); 
$client->request('GET', '/stream/20', ['sink' => $resource]); 

传递一个Psr\Http\Message\StreamInterface对象以将响应主体流式传输到打开的PSR-7流。

$resource = fopen('/path/to/file', 'w'); 
$stream = GuzzleHttp\Psr7\stream_for($resource); 
$client->request('GET', '/stream/20', ['save_to' => $stream]); 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!