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.jpg
and stores the response in the$response
variable.$image = $response->getBody();
- This extracts the body of the response and stores it in the$image
variable.file_put_contents('image.jpg', $image);
- This saves the image data stored in the$image
variable asimage.jpg
in the same directory.
For more information, see the Guzzle documentation.
More of Php Guzzle
- How to use PHP Guzzle to make a batch request?
- How to update PHP Guzzle?
- How to set a user agent in PHP Guzzle?
- How to stream with PHP Guzzle?
- How to make an asynchronous send with PHP Guzzle?
- How to download a file with Guzzle in PHP?
- How to handle a RequestException with PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
- How to get the response body in PHP Guzzle?
- How to add an SSL certificate to a request with PHP Guzzle?
See more codes...