Guzzle get file and forward it
Asked Answered
A

2

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.

Accalia answered 21/4, 2016 at 13:55 Comment(0)
T
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;
}
Tancred answered 21/4, 2016 at 19:28 Comment(2)
Thanks. Works perfect.Accalia
In addition to this you can use sink option to stream your response right to STDOUT (PHP's predefined constant for the default output stream).Aerogram
P
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());
Philosophy answered 4/3, 2021 at 7:31 Comment(1)
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation 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.Ergosterol

© 2022 - 2024 — McMap. All rights reserved.