9

I have a web-service that gets a file and returns it to the user (based on Symfony). Ever since I used curl to do this.

I just found guzzlehttp and it seems great. However, I do not know how to do this with guzzle without saving the downloaded file (xml or txt) to a local file, read it from the file system a returning it to the user. I want to do this without saving to the file system.

Robin
  • 3,512
  • 10
  • 39
  • 73

2 Answers2

14
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;
}
d.garanzha
  • 813
  • 1
  • 9
  • 15
  • Thanks. Works perfect. – Robin Apr 22 '16 at 07:26
  • In addition to this you can use [`sink` option](http://docs.guzzlephp.org/en/latest/request-options.html#sink) to stream your response right to `STDOUT` (PHP's predefined constant for the default output stream). – Alexey Shokov Aug 01 '16 at 21:45
0
$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());
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – jasie Mar 04 '21 at 09:28