Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 599
Robin Avatar asked Apr 21 '16 13:04

Robin


People also ask

How do I send a file using guzzle?

Sending Requests You can create a request and then send the request with the client when you're ready: use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);

How do I get my status code from response guzzle?

You can use the getStatusCode function. $response = $client->request('GET', $url); $statusCode = $response->getStatusCode(); Note: If your URL redirects to some other URL then you need to set false value for allow_redirects property to be able to detect initial status code for parent URL.

What is the difference between cURL and guzzle?

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. cURL can be classified as a tool in the "File Transfer" category, while Guzzle is grouped under "Microframeworks (Backend)". cURL and Guzzle are both open source tools.


1 Answers

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;
}
like image 140
d.garanzha Avatar answered Nov 08 '22 15:11

d.garanzha