Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 解决PHP中file_get_contents抓取网页中文乱码问题

解决PHP中file_get_contents抓取网页中文乱码问题

发布时间:2018-10-11   编辑:www.jquerycn.cn
jquery中文网为您提供解决PHP中file,get,contents抓取网页中文乱码问题等资源,欢迎您收藏本站,我们将为您提供最新的解决PHP中file,get,contents抓取网页中文乱码问题资源
file_get_contents函数本来就是一个非常优秀的php自带本地与远程文件操作函数,它可以让我们不花吹挥之力把远程数据直接下载,但我在使用它读取网页时会碰到有些页面是乱码了,下面我就来给各位总结具体的解决办法。

根据网上有朋友介绍说原因可能是服务器开了GZIP压缩。

下面是用firebug查看我的博客的头信息,Gzip是开了的。

请求头信息原始头信息

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy4392')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy4392>

Accept text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Connection keep-alive
Cookie __utma=225240837.787252530.1317310581.1335406161.1335411401.1537; __utmz=225240837.1326850415.887.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=任何项目都不会那么简单 site:www.nowamagic.net; PHPSESSID=888mj4425p8s0m7s0frre3ovc7; __utmc=225240837; __utmb=225240837.1.10.1335411401
Host www.111cn.net
User-Agent Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0


可以从header信息中找到 Content-Encoding 项是 Gzip 。

解决办法比较简单。

就是用 curl 代替 file_get_contents 去获取,然后在 curl 配置参数中加一条

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy2119')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy2119>

curl_setopt($ch, CURLOPT_ENCODING, "gzip");

今天用 file_get_contents 抓图片的时候,开始没发现这个问题,废了老大劲才找出来

1. 使用自带的zlib库

如果服务器已经装了zlib库,用下面的代码可以轻易解决乱码问题。

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy4522')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy4522>

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

当然也可以使用curl模块来解决人我的问题这里我给各位推荐一文章,如下你感兴趣的文章

您可能感兴趣的文章:
php file_get_contents函数抓取页面信息的代码
php读取远程文件的三种方法分享
php file_get_contents抓取Gzip网页乱码的解决方法
php网页标题中文乱码如何解决
php file_get_contents抓取页面信息的代码
php中curl、fsocket、file_get_content函数比较
php 获取远程网页内容简单函数
解决PHP中file_get_contents抓取网页中文乱码问题
php file_get_contents抓取https地址报错的解决办法
php file_get_contents函数的使用问题

[关闭]