Home  >  Article  >  Backend Development  >  使用php判断网页是否gzip压缩_php技巧

使用php判断网页是否gzip压缩_php技巧

WBOY
WBOYOriginal
2016-05-17 08:58:50779browse

昨天晚上群里有朋友采集网页时发现file_get_contents 获得的网页保存到本地为乱码,响应的header 里 Content-Encoding:gzip
但在浏览器里看是正常的。
因为我有过相关经验马上发现是网站开启了gzip而file_get_contents 获得的是压缩过的页面,而不是解压过的页面(不知道是不是要file_get_conttents 请求网页时带上相应的参数,直接获得没有被gzip压缩过的网页?)
刚好我前不久刚看到可以用读取文件的前2个字节判断文件类型。群里面的朋友也说gzip压缩过的网页(gbk编码)前2字节是 1F 8B 于是就可以判断网页是否gzip压缩过。
代码如下:

复制代码 代码如下:

//米尔军事网采用 gzip压缩网页
//file_get_contents 直接获得的网页是乱码。
header('Content-Type:text/html;charset=utf-8' );
$url = 'http://www.miercn.com';
$file = fopen($url, "rb");  
//只读2字节  如果为(16进制)1f 8b (10进制)31 139则开启了gzip ;
$bin = fread($file, 2); 
fclose($file);  
$strInfo = @unpack("C2chars", $bin);  
$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);  
$isGzip = 0;  
switch ($typeCode)  
{
    case 31139:      
      //网站开启了gzip
        $isGzip = 1;
        break;
    default:  
        $isGzip = 0;
}  
$url = $isGzip ? "compress.zlib://".$url:$url; // 三元表达式
$mierHtml = file_get_contents($url); //获得米尔军事网数据
$mierHtml = iconv("gbk","utf-8",$mierHtml);
echo $mierHtml;

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn