How can I upload files asynchronously using Guzzle 6?

I'm trying to download files asynchronously using Guzzle 6, but the documentation seems vague and cannot find useful examples.

What I'm not sure about is how should I save the received data?

I am currently doing it like this:

$successHandler = function (Response $response, $index) use ($files) { $file = fopen($files[$index], 'a'); $handle = $response->getBody(); while (!$handle->eof()) { fwrite($file, $handle->read(2048)); } fclose($file); }; 

Is it really asynchronous?

Since if we enter one callback and start a loop, how can we get data from others at the same time?

Is there a more direct way to say when a request is made, where should the response be stored? (or directly passing the stream for this).

+5
source share
2 answers

The sink parameter should be your friend here:

 $client->request('GET', '/stream/20', [ 'sink' => '/path/to/file', ]); 

For reference, see http://docs.guzzlephp.org/en/latest/request-options.html#sink .

+9
source
 use function GuzzleHttp\Psr7\stream_for; use GuzzleHttp\RequestOptions; use GuzzleHttp\Client; $tmpFile = tempnam(sys_get_temp_dir(), uniqid(strftime('%G-%m-%d'))); $resource = fopen($tmpFile, 'w'); $stream = stream_for($resource); $client = new Client(); $options = [ RequestOptions::SINK => $stream, // the body of a response RequestOptions::CONNECT_TIMEOUT => 10.0, // request RequestOptions::TIMEOUT => 60.0, // response ]; $response = $client->request('GET', 'https://github.com/robots.txt', $options); $stream->close(); fclose($resource); if ($response->getStatusCode() === 200) { echo file_get_contents($tmpFile); // content } 
+1
source

All Articles