Vladislav Rastrusny Vladislav Rastrusny - 22 days ago 10
PHP Question

Guzzle: Parallel file download using Guzzle's Pool:batch() and `sink` option

You can execute http requests in parallel using Guzzle's

Pool:batch()
method. It allows you to set default options for requests using
options
key in the third parameter.

But what if I need different options for different requests in the pool? I would like to execute GET requests using a pool and stream each response to a different file on disk. There is a
sink
option for that. But how to apply different values of this option to requests?

Answer

For guzzle 6

$client = new \GuzzleHttp\Client();

$requests = function ($total) use ($client) {
    for ($i = 0; $i < $total; $i++) {
        $url = "http://domain.com/picture/{$i}.jpg";
        $filepath = "/tmp/{$i}.jpg";

        yield function() use ($client, $url, $filepath) {
            return $client->getAsync($url, [
                'sink' => $filepath
            ]);
        };
    }
};

$pool = new Pool($client, $requests(100));