php-guzzleHow to use Guzzle in PHP to make an asynchronous request?
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. It can be used to make asynchronous requests in PHP.
Example code
$client = new GuzzleHttp\Client();
$promise = $client->requestAsync('GET', 'http://www.example.com');
$promise->then(
function ($response) {
echo 'I completed! ' . $response->getBody();
},
function ($exception) {
echo 'I failed! ' . $exception->getMessage();
}
);
Output example
I completed! <html>...</html>
Code explanation
$client = new GuzzleHttp\Client();
: Create a new Guzzle client.$promise = $client->requestAsync('GET', 'http://www.example.com');
: Make an asynchronous request to the given URL.$promise->then(...)
: Register a callback to be executed when the request is completed.function ($response) {...}
: Callback to be executed when the request is successful.function ($exception) {...}
: Callback to be executed when the request fails.
Helpful links
More of Php Guzzle
- How to use PHP Guzzle to make a batch request?
- How to set a user agent in PHP Guzzle?
- How to convert a response to an array with PHP Guzzle?
- How to send multipart requests with Guzzle in PHP?
- How to make HTTP request with PHP Guzzle?
- How to post form data with PHP Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
- How to log requests with Guzzle in PHP?
- How to use multipart/form-data with PHP Guzzle?
- How to send multiple requests with Guzzle in PHP?
See more codes...