当file_get_contents或者simplexml_load_file的时候乱码

来源:互联网 发布:行政审批流程优化方案 编辑:程序博客网 时间:2024/04/29 03:17

乱码有几种可能如下:

1.页面能获取过来,只是内容乱码而已:可以采用iconv()和mb_convert_encoding()函数进行转码即可

2.当内容都无法正常获取的时候,分两种情况第一种是防盗链,第二种是页面需要解压

2.1防盗链情况下解决办法比较简单,模拟浏览器就可以了

  1. <?php  
  2.     header('content-type:text/html;charset=utf-8');  
  3.     $url="http://www.sohu.com/";  
  4.     ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;)');  
  5.     $html=file_get_contents($url);  
  6.     //echo $html;  
  7.     echo mb_convert_encoding($html,'utf8','gbk'); 
2.2需要解压时,我们可以用以下方式

  1. <?php  
  2. header("content-type:text/html;charset=utf-8");  
  3. $url="http://wthrcdn.etouch.cn/WeatherApi?city=%E5%8C%97%E4%BA%AC";  
  4. $xml = simplexml_load_file("compress.zlib://".$url);  
  5. $json=json_encode($xml);  
  6. $arr=json_decode($json,true);  
  7. print_r($arr);
curl添加参数方式模拟浏览器和解压链接  http://blog.csdn.net/zph1234/article/details/50855740

0 0
原创粉丝点击