您的位置 首页 php

PHP模拟浏览器访问,抓取非本地文件的几种方法「爬虫」

PHP模拟浏览器访问,抓取非本地文件的几种方法「爬虫」

在做一些天气预报或者RSS订阅的程序时,往往需要抓取非本地文件,一般情况下都是利用php模拟浏览器的访问,通过http请求访问url地址, 然后得到html源代码或者xml数据,得到数据我们不能直接输出,往往需要对内容进行提取,然后再进行格式化,以更加友好的方式显现出来。

PHP模拟浏览器访问,抓取非本地文件的几种方法「爬虫」

下面简单说一下php抓取页面的几种方法及原理:

一、 PHP抓取页面的主要方法:

1. file()函数

2. file_get_contents()函数

3. fopen()->fread()->fclose()模式

4.curl方式

5. fsockopen()函数 socket模式

6. 使用插件(如:

二、PHP解析html或xml代码主要方式:

1. file()函数

<?php 
$url=' 
$lines_array=file($url); 
$lines_string=implode('',$lines_array); 
echo htmlspecialchars($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都不能打开远程文件。

<?php 
$url=' 
$lines_string=file_get_contents($url); 
echo htmlspecialchars($lines_string); 
 

3. fopen()->fread()->fclose()模式

<?php 
$url=' 
$handle=fopen($url,"rb"); 
$lines_string=""; 
do{ 
 $data=fread($handle,1024);
 if(strlen($data)==0) {
 break;
 } 
 $lines_string.=$data; 
}while(true); 
fclose($handle); 
echo htmlspecialchars($lines_string);
 

4. curl方式

使用curl必须空间开启curl。方法:windows下修改php.ini,将extension=php_curl. dll 前面的分号去掉,而且需 要拷贝ssleay32.dll和libeay32.dll到C:WINDOWSsystem32下;Linux下要安装curl扩展。

<?php 
$url=' 
$ch=curl_init(); 
$timeout=5; 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
$lines_string=curl_exec($ch); 
curl_close($ch); 
echo htmlspecialchars($lines_string);
 

5. fsockopen()函数 socket模式

socket模式能否正确执行,也跟服务器的设置有关系,具体可以通过phpinfo查看服务器开启了哪些通信协议,比如我的本地php socket没开启http,只能使用udp测试一下了。

<?php 
$fp = fsockopen("udp://127.0.0.1", 13, $ errno , $errstr);
if (!$fp) { 
 echo "ERROR: $errno - $errstr<br />n"
} else { 
 fwrite($fp, "n")
 echo fread($fp, 26)
 fclose($fp)
} 
 
PHP模拟浏览器访问,抓取非本地文件的几种方法「爬虫」

如果想要学习交流PHP的朋友,可以关注小编,私信【学习交流】手机用户可以直接私信,电脑端尚未开放此功能,需要下载app,我已经设置了自动回复,具体后续会自动回复各位。

PHP模拟浏览器访问,抓取非本地文件的几种方法「爬虫」

文章来源:智云一二三科技

文章标题:PHP模拟浏览器访问,抓取非本地文件的几种方法「爬虫」

文章地址:https://www.zhihuclub.com/78491.shtml

关于作者: 智云科技

热门文章

评论已关闭

3条评论

  1. Sweet blog! I found it while searching on Yahoo News.

    Do you have any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!
    Appreciate it

  2. You really make it seem so easy with your presentation however I find this matter
    to be really something that I believe I would
    never understand. It sort of feels too complex and extremely large for me.
    I’m looking forward in your next publish, I’ll attempt to get the cling of it!

  3. What’s up, just wanted to tell you, I enjoyed this post.
    It was helpful. Keep on posting!

网站地图