我正在通过 curl 检索一个 gzipped 网页,但是当我将检索到的内容输出到浏览器时,我只得到原始 gzipped 数据。如何解码 PHP 中的数据?
我发现的一种方法是将内容写入 tmp 文件,然后...
$f = gzopen($filename,"r");
$content = gzread($filename,250000);
gzclose($f);
....但是伙计,必须有更好的方法。
编辑:这不是一个文件,而是一个由网络服务器返回的压缩 html 页面。
我使用 curl 并且:
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
多功能 GUNZIP 功能:
函数 gunzip($zipped) {
$偏移量 = 0;
if (substr($zipped,0,2) == "\x1f\x8b")
$偏移量 = 2;
if (substr($zipped,$offset,1) == "\x08") {
# file_put_contents("tmp.gz", substr($zipped, $offset - 2));
返回 gzinflate(substr($zipped, $offset + 8));
}
返回“未知格式”;
}
将函数与 CURL 集成的示例:
$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];
if (preg_match('/^Content-Encoding: gzip/mi', $headers)) {
printf("找到 gzip 头\n");
返回 gunzip($data);
}
}
返回 $ret;