16

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;
    ?>
Alexey Shokov
  • 4,775
  • 1
  • 21
  • 22
Kevin Lindmark
  • 1,155
  • 3
  • 13
  • 26

3 Answers3

44

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]);
Chris
  • 1,140
  • 15
  • 30
  • Good answer, helped med also find the stream solution. Thanks! – Kevin Lindmark Aug 22 '19 at 11:19
  • 2
    Good answer, I would just point out that if you do not store response to a local variable, it goes out of scope and resource is closed before you can work with it. – Vody May 05 '20 at 09:33
  • 1
    Is it really needed to save the response on disk? Can't I just return the response to the client directly without saving it? – Ionel Lupu Dec 09 '21 at 17:10
6

stream_for is deprecated in version 7.2. You can use GuzzleHttp\Psr7\Utils::streamFor($resource) instead.

Nzbuu
  • 5,241
  • 1
  • 29
  • 51
-1

First of all, Content-Type header only makes sense when you send something (POST/PUT), but not for GET requests.

Secondly, what is your issue? Guzzle by default does not store the response body (file) somewhere, so you can work with it inside your app, like $responsesfile->getBody().

Alexey Shokov
  • 4,775
  • 1
  • 21
  • 22