Search code examples
symfonycurlguzzleguzzle6

Guzzle get file and forward it


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.


Solution

  • 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;
    }