php-guzzleHow to make HTTP request with PHP Guzzle?
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.
To make an HTTP request with Guzzle, you need to create a GuzzleHttp\Client
object and pass it the base URI of the web service you are trying to access.
$client = new GuzzleHttp\Client(['base_uri' => 'http://httpbin.org/']);
Then you can use the $client
object to make an HTTP request. For example, to make a GET request:
$response = $client->request('GET', 'get');
echo $response->getBody();
The output of the above code will be a JSON string containing the response from the web service:
{
"args": {},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"User-Agent": "GuzzleHttp/6.3.3 curl/7.54.0 PHP/7.2.10"
},
"origin": "1.2.3.4",
"url": "http://httpbin.org/get"
}
Code explanation
-
$client = new GuzzleHttp\Client(['base_uri' => 'http://httpbin.org/']);
- creates aGuzzleHttp\Client
object and passes it the base URI of the web service you are trying to access. -
$response = $client->request('GET', 'get');
- uses the$client
object to make an HTTP request. In this case, it is a GET request. -
echo $response->getBody();
- prints out the response from the web service.
Helpful links
More of Php Guzzle
- How to send multipart requests with Guzzle in PHP?
- How to use PHP Guzzle to make a batch request?
- How to set a user agent in PHP Guzzle?
- How to update PHP Guzzle?
- How to handle a RequestException with PHP Guzzle?
- How to use a proxy with Guzzle in PHP?
- How to add an SSL certificate to a request with PHP Guzzle?
- How to add query parameters to a request with PHP Guzzle?
- How to use cookies with Guzzle in PHP?
See more codes...