Home > php教程 > php手册 > PHP采集(远程抓取) 自定义函数

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

WBOY
Release: 2016-06-07 11:40:47
Original
1381 people have browsed it

PHP采集(远程抓取) 自定义函数
在采集的时候,我们经常用到file_get_contents或CURL在写代码的时候,或者大家经常遇到问题,反复的调试,下面我自己写了一个函数,可以节省时间,这也是我自己用的,送给大家交流/*<br>  * 远程抓取数据函数<br>  * <br>  * $url           远程URL地址 必选 <br>  * $way         1为file_get_contents抓取  2为CURL抓取  默认为1 可留空<br>  * $$coding  编码  1为UTF-8转GBK  1为GBK转UTF-8  留空为不转换<br>  * <br>  * 作者: 小曾  QQ839024615 欢迎加我一起交流!<br>  * <br>  */<br> <br> function GetFile($url,$way=1,$coding){<br>     if($way==1){<br>         $str=file_get_contents($url);<br>     }else if($way==2){<br>         @$ch=curl_init();<br>         curl_setopt($ch,CURLOPT_URL,$url);<br>         curl_setopt($ch,CURLOPT_HEADER,0);<br>         curl_setopt($ch,CURLOPT_NOBODY,false); <br>         curl_setopt($ch,CURLOPT_TIMEOUT,3);<br>         curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);<br>         curl_setopt($ch,CURLOPT_MAXREDIRS,20);<br>         curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);<br>         curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.0)");<br>         $orders=@curl_exec($ch);<br>         @curl_close($ch);<br>         $str=$orders;<br>     }<br>     if($coding=="1"){<br>         $str=iconv("UTF-8", "GBK", $str);<br>     }elseif ($coding=="2"){<br>         $str=iconv("GBK", "UTF-8", $str);<br>     }<br>     return $str;<br> }<br> //使用方法<br> echo GetFile("http://www.thinkphp.cn",2,1); //采集thinkphp官网 CURL 转GBK编码

AD:真正免费,域名+虚机+企业邮箱=0元

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template