Guzzle 6 download file

Kevin Lindmark picture Kevin Lindmark · Aug 20, 2019 · Viewed 14.5k times · Source

Need help using Guzzle 6 for downloading a file from a rest API. I don't want the file to be saved locally but downloaded from web browser. Code so far below, but believe I am missing something?

    <?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;
    ?>

Answer

Chris picture Chris · Aug 22, 2019

Just do research inside Guzzle's docs, for example here

Pass a string to specify the path to a file that will store the contents of the response body:

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

Pass a resource returned from fopen() to write the response to a PHP stream:

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

Pass a Psr\Http\Message\StreamInterface object to stream the response body to an open PSR-7 stream.

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