解码通过cURL在PHP中检索的gzip网页
我正在通过curl检索一个gzipped网页,但是当我将检索到的内容输出到浏览器时,我只是得到了原始gzip的数据。 我如何解码PHP中的数据?
我发现的一种方法是将内容写入一个tmp文件,然后…
$f = gzopen($filename,"r"); $content = gzread($filename,250000); gzclose($f);
但是,男人应该有更好的办法。
编辑:这不是一个文件,而是一个网页服务器返回的gzipped html页面。
我使用curl和:
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
在PHP页面的gzdecode的评论中提出了几个解决scheme。
多function的GUNZIPfunction:
函数gunzip($ zip){
$ offset = 0;
if(substr($ zip,0,2)==“\ x1f \ x8b”)
$ offset = 2;
if(substr($ zip,$ offset,1)==“\ x08”){
#file_put_contents(“tmp.gz”,substr($ zip,$ offset - 2));
返回gzinflate(substr($ zip,$ offset + 8));
}
返回“未知格式”;
}
集成CURLfunction的示例:
$ headers_enabled = 1;
curl_setopt($ c,CURLOPT_HEADER,$ headers_enabled)
$ ret = curl_exec($ c);
如果($ 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];
如果(preg_match('/ ^ Content-Encoding:gzip / mi',$ headers)){
printf(“findgzip头文件\ n”);
返回gunzip($ data);
}
}
返回$ ret;