php-guzzleHow to use PHP Guzzle to make a batch request?
PHP Guzzle can be used to make batch requests. This is done by creating an array of requests and passing it to the send()
method of the GuzzleHttp\Client
class.
$client = new GuzzleHttp\Client();
$requests = [
'req1' => $client->getAsync('http://httpbin.org/get'),
'req2' => $client->getAsync('http://httpbin.org/get?foo=bar'),
'req3' => $client->getAsync('http://httpbin.org/get?baz=bam')
];
$results = GuzzleHttp\Promise\unwrap($requests);
The output of the above code will be an array of responses:
Array
(
[req1] => GuzzleHttp\Psr7\Response Object
(
[reasonPhrase:GuzzleHttp\Psr7\Response:private] => OK
...
)
[req2] => GuzzleHttp\Psr7\Response Object
(
[reasonPhrase:GuzzleHttp\Psr7\Response:private] => OK
...
)
[req3] => GuzzleHttp\Psr7\Response Object
(
[reasonPhrase:GuzzleHttp\Psr7\Response:private] => OK
...
)
)
Code explanation
$client = new GuzzleHttp\Client();
- This creates a new instance of theGuzzleHttp\Client
class.$requests = [ ... ]
- This creates an array of requests.$results = GuzzleHttp\Promise\unwrap($requests);
- This sends the requests and returns an array of responses.
Helpful links
More of Php Guzzle
- How to set a user agent in PHP Guzzle?
- How to update PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to add query parameters to a request with PHP Guzzle?
- How to use multipart/form-data with PHP Guzzle?
- How to add an SSL certificate to a request with PHP Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
- How to set Guzzle options in PHP?
- How to send multipart requests with Guzzle in PHP?
See more codes...