php-guzzleHow to download an image with Guzzle in PHP?
Using Guzzle in PHP to download an image is easy. Here is an example code block to do so:
$client = new GuzzleHttp\Client();
$response = $client->request('GET', 'http://example.com/image.jpg');
$image = $response->getBody();
file_put_contents('image.jpg', $image);
This code will download the image from the URL http://example.com/image.jpg and save it as image.jpg in the same directory.
The code consists of the following parts:
$client = new GuzzleHttp\Client();- This creates a new Guzzle client.$response = $client->request('GET', 'http://example.com/image.jpg');- This sends a GET request to the URLhttp://example.com/image.jpgand stores the response in the$responsevariable.$image = $response->getBody();- This extracts the body of the response and stores it in the$imagevariable.file_put_contents('image.jpg', $image);- This saves the image data stored in the$imagevariable asimage.jpgin the same directory.
For more information, see the Guzzle documentation.
More of Php Guzzle
- What version of PHP is required for Guzzle?
- How to set a user agent in PHP Guzzle?
- How to log requests with Guzzle in PHP?
- How to use PHP Guzzle to make a batch request?
- How to keep alive with Guzzle in PHP?
- How to add an SSL certificate to a request with PHP Guzzle?
- How to install PHP Guzzle without Composer?
- How to stream with PHP Guzzle?
- How to convert a response to an array with PHP Guzzle?
- How to make an asynchronous send with PHP Guzzle?
See more codes...