Get compressed content with file_get_contents()

application, gnome, gzip, mime iconThe file_get_contents() function in PHP is used to get the source code of a webpage.
echo file_get_contents('http://www.imdb.com/');
The above code will echo the whole webpage.

However the file_get_contents() function does not get the content in a compressed way. It requests the server to send everything in plain text format. Compressing the content saves bandwidth and speeds up the transfer process. Sending a specific HTTP header that instructs the remote server to provide compressed content does the job. Then the compressed content has to be uncompressed too to convert to original form. The code that will make this happen goes as follows:

<?php
function get_compressed($url)
{
    $opts = array(
        'http'=>array(
            'method'=>"GET",
            'header'=>"Accept-Language: en-US,en;q=0.8rn" .
                        "Accept-Encoding: gzip,deflate,sdchrn" .
                        "Accept-Charset:UTF-8,*;q=0.5rn" .
                        "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:19.0) Gecko/20100101 Firefox/19.0 FirePHP/0.4rn"
        )
    );

    $context = stream_context_create($opts);
    $content = file_get_contents($url ,false,$context); 
     
    foreach($http_response_header as $c => $h)
    {
        if(stristr($h, 'content-encoding') and stristr($h, 'gzip'))
        {
            $content = gzinflate( substr($content,10,-8) );
        }
    }
    return $content;
}

echo get_compressed('http://www.google.com/');
?>

The function first sends the "Accept-Encoding" header in the request. If the server replies with content encoded with gzip, it inflates the content back. That's all.
Emoticon? Emoticon

Komentar Terbaru

Just load it!