php file_get_contents读取远程文件的乱码问题(gzip压缩引起的)

    昨天发现以前做的调用 中国天气网的天气api,保存到本地发现有部分城市是乱码。

一直找不到原因。因为在浏览器看 完全正常。 如。读取 银川市的当天天气  http://m.weather.com.cn/data/101170101.html 

 

在浏览器上看它的json数据 完全正常。编码也正常。但用file_get_contents 读取在浏览器输出就是乱码。

 

$url = 'http://m.weather.com.cn/data/101170101.html';
echo '<pre>';
print_r(file_get_contents($url));

 

 

在网上忙活一阵才发现 原因 中国天气网开启了gzip压缩 。找到了解决方法   来自 http://www.php10086.com/2012/03/516.html

PHP的file_get_contents获取远程页面内容,如果是gzip编码过的,返回的字符串就是编码后的乱码,如何解决gzip问题方法有两种:

curl解决:

 

function curl_get($url, $gzip=false){
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
        if($gzip) curl_setopt($curl, CURLOPT_ENCODING, "gzip"); // 关键在这里
        $content = curl_exec($curl);
        curl_close($curl);
        return $content;
}

采用gzip编码格式

file_get_contents解决:

 

file_get_contents("compress.zlib://".$url);

无论页面是否经过gzip压缩,上述代码都可以正常工作!

PHP 4.3.0以后版本支持,还可以用于fopen之类的函数~!

 

解决方法:

$url = 'http://m.weather.com.cn/data/101170101.html';

echo '<pre>'; 

print_r(file_get_contents("compress.zlib://".$url));//打开gzip压缩过的页面。 路径前不加compress.zlib:// 打开会有乱码。  
posted @ 2012-08-16 12:04  keygle  阅读(4125)  评论(0编辑  收藏  举报