DEV Community

adithyasrinivasan
adithyasrinivasan

Posted on • Originally published at adithya.dev on

Decode GZIP response in Laravel

If you try to decode a GZIP response without decoding, you will have seen this error

XMLReader::read(): /var/www/html/:1: parser error : Document is empty {"exception":"[object] (ErrorException(code: 0): XMLReader::read(): /var/www/html/:1: parser error : Document is empty at
Enter fullscreen mode Exit fullscreen mode

To decode a XML ZIP response in Guzzle, you can do this as recommended by the documentation

// Request gzipped data, but do not decode it while downloading
$client->request('GET', 'foo.xml.gz', [
    'headers' => ['Accept-Encoding' => 'gzip'],
    'decode_content' => false
]);
Enter fullscreen mode Exit fullscreen mode

When set to a string, the bytes of a response are decoded and the string value provided to the decode_content option is passed as the Accept-Encoding header of the request.

// Pass "gzip" as the Accept-Encoding header.
$client->request('GET', 'foo.xml.gz', ['decode_content' => 'gzip']);
Enter fullscreen mode Exit fullscreen mode

Laravel provides useful header methods via its HTTP client.

$response = Http::withOptions([
            'decode_content' => 'gzip'
        ])->get('foo.xml.gz');
Enter fullscreen mode Exit fullscreen mode

or using headers, this can be

   $response = Http::accept('gzip')
                ->get('foo.xml.gz');

Enter fullscreen mode Exit fullscreen mode

Discussion (0)