When retrieving gzipped web pages using cURL, the raw data may be outputted instead of the decoded content. Resolving this can be achieved using the following methods:
cURL's "auto encoding" mode allows the server to determine the supported encoding methods and automatically decompress the response. To activate this mode, use the following command:
<code class="php">curl_setopt($ch, CURLOPT_ENCODING, '');</code>
By setting the CURLOPT_ENCODING option to an empty string, cURL will use "auto" mode.
Alternatively, you can force the request to use GZIP compression by setting the CURLOPT_ENCODING option to 'gzip':
<code class="php">curl_setopt($ch, CURLOPT_ENCODING, 'gzip');</code>
This will explicitly request GZIP compression from the server.
If you need to manually decompress the retrieved data, you can use the gzdecode() function:
<code class="php">$decompressedContent = gzdecode($gzippedContent);</code>
This function decodes GZIP-compressed data and returns the uncompressed content.
To ensure reliable decompression, it's recommended to disable PHP's output buffering before executing the curl request. This prevents any interference with cURL's handling of the response.
<code class="php">ob_end_clean();</code>
The above is the detailed content of How to Decompress Gzipped Web Pages Retrieved via cURL in PHP?. For more information, please follow other related articles on the PHP Chinese website!