How do I handle gzip or deflate compressed responses in Guzzle?

Guzzle is a PHP HTTP client that simplifies making HTTP requests from PHP applications. It supports automatic decompression of HTTP responses. When a server responds with Content-Encoding: gzip or Content-Encoding: deflate, Guzzle can handle these compressed responses transparently so that you can work with the uncompressed content directly.

By default, Guzzle automatically adds the Accept-Encoding header to outgoing requests to tell the server that it can accept compressed content. When the server responds with compressed content, Guzzle will automatically decompress it.

Here's how you can make a request with Guzzle and handle gzip or deflate compressed responses:

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

$client = new Client();

try {
    $response = $client->request('GET', 'http://example.com', [
        // 'decode_content' is set to true by default, enabling automatic decompression.
        'decode_content' => true
    ]);

    // This will contain the decompressed response body if the server sent compressed content.
    $body = $response->getBody()->getContents();

    echo $body;
} catch (RequestException $e) {
    echo $e->getMessage();
}

In the example above, decode_content is set to true by default, which tells Guzzle to automatically handle decompression. If you want to explicitly disable this behavior for some reason, you can set decode_content to false in the request options.

If you need to work with the raw compressed data, you can disable automatic decompression by setting decode_content to false, like this:

$response = $client->request('GET', 'http://example.com', [
    'decode_content' => false
]);

// This will contain the raw compressed response body.
$compressedBody = $response->getBody()->getContents();

Remember that when you disable automatic decompression, you will need to manually handle the compressed data if the server sends it.

For most use cases, you shouldn't need to worry about the compression details. Guzzle's default behavior will take care of it for you, allowing you to focus on what you want to do with the content of the response.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon