PHP采集(远程抓取) 自定义函数

jerry thinkphp 2015年11月19日 收藏
PHP采集(远程抓取) 自定义函数
在采集的时候,我们经常用到file_get_contents或CURL在写代码的时候,或者大家经常遇到问题,反复的调试,下面我自己写了一个函数,可以节省时间,这也是我自己用的,送给大家交流
  1. /*
  2.  * 远程抓取数据函数
  3.  * 
  4.  * $url           远程URL地址 必选 
  5.  * $way         1为file_get_contents抓取  2为CURL抓取  默认为1 可留空
  6.  * $$coding  编码  1为UTF-8转GBK  1为GBK转UTF-8  留空为不转换
  7.  * 
  8.  * 作者: 小曾  QQ839024615 欢迎加我一起交流!
  9.  * 
  10.  */

  11. function GetFile($url,$way=1,$coding){
  12.     if($way==1){
  13.         $str=file_get_contents($url);
  14.     }else if($way==2){
  15.         @$ch=curl_init();
  16.         curl_setopt($ch,CURLOPT_URL,$url);
  17.         curl_setopt($ch,CURLOPT_HEADER,0);
  18.         curl_setopt($ch,CURLOPT_NOBODY,false); 
  19.         curl_setopt($ch,CURLOPT_TIMEOUT,3);
  20.         curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
  21.         curl_setopt($ch,CURLOPT_MAXREDIRS,20);
  22.         curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  23.         curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.0)");
  24.         $orders=@curl_exec($ch);
  25.         @curl_close($ch);
  26.         $str=$orders;
  27.     }
  28.     if($coding=="1"){
  29.         $str=iconv("UTF-8", "GBK", $str);
  30.     }elseif ($coding=="2"){
  31.         $str=iconv("GBK", "UTF-8", $str);
  32.     }
  33.     return $str;
  34. }
  35. //使用方法
  36. echo GetFile("http://www.thinkphp.cn",2,1); //采集thinkphp官网 CURL 转GBK编码