这篇文章讲的是PHP爬取网页的主要方法,主要流程就是获取整个网页,然后正则匹配(关键的)。
PHP抓取页面的主要方法,有几种方法是网上前辈的经验,现在还没有用到的,先存下来以后试试。
- file()函数
- file_get_contents()函数
- fopen()->fread()->fclose()模式
- curl方式 (本人主要用这个)
- fsockopen()函数 socket模式
- 插件(如:http://sourceforge.net/projects/snoopy/)
不要走开,接下来就分别来看看这六种方法,你掌握了几个?
1.file()函数
<?php
//定义url
$url='[http://t.qq.com](http://t.qq.com/)';//fiel函数读取内容数组
$lines_array=file($url);//拆分数组为字符串
$lines_string=implode('',$lines_array);//输出内容
echo $lines_string;
2.使用file_get_contents方法实现,比较简单。
使用 file_get_contents 和fopen必须空间开启 allow_url_fopen 。方法:编辑php.ini,设置 allow_url_fopen = On,allow_url_fopen 关闭时fopen和 file_get_contents 都不能打开远程文件。
$url="[http://news.sina.com.cn/c/nd/2016-10-23/doc-ifxwztru6951143.shtml](http://news.sina.com.cn/c/nd/2016-10-23/doc-ifxwztru6951143.shtml)";
$html=file_get_contents($url);
//如果出现中文乱码使用下面代码`
//$getcontent = iconv("gb2312", "utf-8",$html);
echo"<textarea style='width:800px;height:600px;'>".$html."</textarea>";
3.fopen()->fread()->fclose()模式 ,目前还没用过,看到了就先记下了
<?php
//定义url
$url='[http://t.qq.com](http://t.qq.com/)';//fopen以二进制方式打开
$handle=fopen($url,"rb");//变量初始化
$lines_string="";//循环读取数据
do{
$data=fread($handle,1024);
if(strlen($data)==0) {
`
break;
}
$lines_string.=$data;
}while(true);//关闭fopen句柄,释放资源