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

来源:互联网 发布:公司制律师事务所知乎 编辑:程序博客网 时间:2024/06/05 04:34
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