Decoding a gzipped webpage obtained via cURL in PHP

I retrieve the gzipped web page through curl, but when I output the received content to the browser, I just get the raw gzipped data. How can I decode data in PHP?

One of the methods I found is to write the contents to a tmp file, and then ...

$f = gzopen($filename,"r"); $content = gzread($filename,250000); gzclose($f); 

.... but man, there must be a better way.

Edit: this is not a file, but a gzipped html page returned by the web server.

+44
php encoding gzip decoding
Nov 22 '08 at 0:50
source share
3 answers

I use curl and:

 curl_setopt($ch,CURLOPT_ENCODING , "gzip"); 
+98
May 17 '10 at 13:21
source share

The comments on the PHP page for gzdecode offer several solutions.

+2
Nov 22 '08 at 5:15
source share

Universal function of GUNZIP:

    function gunzip ($ zipped) {
       $ offset = 0;
       if (substr ($ zipped, 0,2) == "\ x1f \ x8b")
          $ offset = 2;
       if (substr ($ zipped, $ offset, 1) == "\ x08") {
          # file_put_contents ("tmp.gz", substr ($ zipped, $ offset - 2));
          return gzinflate (substr ($ zipped, $ offset + 8));
       }
       return "Unknown Format";
    }  

An example of an integrating function with CURL:

       $ headers_enabled = 1;
       curl_setopt ($ c, CURLOPT_HEADER, $ headers_enabled)
       $ ret = curl_exec ($ c);

       if ($ headers_enabled) {
          # file_put_contents ("preungzip.html", $ ret);

          $ sections = explode ("\ x0d \ x0a \ x0d \ x0a", $ ret, 2);
          while (! strncmp ($ sections [1], 'HTTP /', 5)) {
             $ sections = explode ("\ x0d \ x0a \ x0d \ x0a", $ sections [1], 2);
          }
          $ headers = $ sections [0];
          $ data = $ sections [1];

          if (preg_match ('/ ^ Content-Encoding: gzip / mi', $ headers)) {
             printf ("gzip header found \ n");
             return gunzip ($ data);
          }
       }

       return $ ret;
+2
Jan 30 '11 at 7:27
source share



All Articles