How to download and save an image from a URL using Guzzle in PHP?

To download and save an image from a URL using Guzzle in PHP, you can follow these steps:

  1. Make sure you have Guzzle installed in your PHP project. You can install it using Composer with the following command:
composer require guzzlehttp/guzzle
  1. Create a PHP file and include the autoloader file generated by Composer:
require 'vendor/autoload.php';
  1. Initialize a new instance of the Guzzle client:
$client = new GuzzleHttp\Client();
  1. Specify the URL of the image you want to download:
$imageUrl = 'https://example.com/path/to/image.jpg';
  1. Use the Guzzle client to send a GET request to the image URL and retrieve its response:
$response = $client->get($imageUrl);
  1. Get the contents of the response body and save it to a file:
$imageContents = $response->getBody()->getContents(); file_put_contents('path/to/save/image.jpg', $imageContents);

Make sure to replace 'https://example.com/path/to/image.jpg' with the actual URL of the image you want to download, and 'path/to/save/image.jpg' with the desired path and filename to save the image.

After running this PHP script, the image will be downloaded from the URL and saved to the specified file path.