php采集页面内容并自动转码

  1. /*
  2.  * 用法 get_contents('www.yi210.com', 'utf-8');
  3.  * 采集页面内容并自动转码
  4.  * get_contents()自定义函数
  5.  * $url 需要采集的页面地址
  6.  * $timeout 超时时间,默认20 
  7.  */
  8.  function get_contents($url, $timeout = 20)
  9.  {
  10.     if( function_exists('curl_init') ){
  11.         $ch = curl_init();
  12.         curl_setopt( $ch, CURLOPT_URL, $url );
  13.         curl_setopt( $ch, CURLOPT_HEADER, false );
  14.         curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
  15.         curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); 
  16.         curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );    
  17.         $content = curl_exec( $ch );
  18.         curl_close( $ch );
  19.         $data = $content ? $content : false;
  20.     } else {
  21.         //利用了stream_context_create()设置超时时间:
  22.         $pots = array(
  23.             'http' => array(
  24.                 'timeout' => $timeout
  25.                 )
  26.             );
  27.         $context = stream_context_create( $pots );
  28.         $content = @file_get_contents( $url, false, $context );
  29.         $data = $content ? $content : false;
  30.     }    
  31.     return $data ? my_encoding( $content, 'utf-8' ) : false;
  32.  }
  33.  /*
  34.  * 页面内容并自动转码
  35.  * my_encoding()自定义函数
  36.  * $data 为 curl_exec() 或 file_get_contents() 所获得的页面内容
  37.  * $to 需要转成的编码
  38.  */
  39.  function my_encoding( $data, $to )
  40.  {
  41.     $encode_arr = array('UTF-8','ASCII','GBK','GB2312','BIG5','JIS','eucjp-win','sjis-win','EUC-JP');
  42.     $encoded = mb_detect_encoding($data, $encode_arr);
  43.     $data = mb_convert_encoding($data,$to,$encoded);
  44.     return $data;
  45.  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值