PHP 实现抓取页面与代码解析
2012-01-11 11:08
linux.chinaitlabEmmanuel 字号: A+ | A在做一些天气预报或者 RSS 订阅的
程序时,往往需要抓取非本地文件,一般 情况下都是利用 php 模拟浏览器的访问,通过 http 请求访问 url 地址, 然后得 到 html
源代码或者 xml 数据,得到数据我们不能直接输出,往往需要对内容进 行提取,然后再进行格式化,以更加友好的方式显现出来。 一、 PHP 抓取页面的主要方法: 1. file()函数 2. file_get_contents()函数 3. fopen()->fread()->fclose()模式 4.curl 方式 5. fsockopen()函数 socket 模 式 6. 使用插件(如:sourceforge.net/projects/snoopy/) 二、PHP 解析 html 或 xml 代码主要方式: 1. 正则表达式 2. PHP DOMDocument 对象 3. 插件(如:) 如果你对以上内容已经很了解,以下内容可以飘过……
PHP 抓取页面 1. file()函数<?php $url='t.qq'; $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='t.qq'; $lines_string=file_get_contents($url); echo htmlspecialchars($lines_string); ?> 3. fopen()->fread()->fclose()模式 <?php $url='t.qq'; $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:\WINDOWS\system32 下;Linux 下要安装 curl 扩展。
<?php $url='t.qq'; $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 \n"; } else { fwrite($fp, "\n"); echo fread($fp, 26); fclose($fp); } ?> 6. 插件网上应该有比较多的插件,snoopy 插件是在网上 搜到的,有兴趣的可以研究一下。 PHP 解析
xml(html) 1. 正则表达式:<?php $url='t.qq'; $lines_string=file_get_contents($url); eregi('', $lines_string, $title); echo htmlspecialchar
s($title[0]); ?> 2. PHP DOMDocument()对象如果远程 的 html 或 xml 存在语法错误,php 在解析 dom 的时候会报错。 <?php $url='136
web'; $html=new DOMDocument(); $html->loadHTMLFile($url); $title=$html->getElementsByTagName('title'); echo $title->item(0)->nodeValue; ?> 3. 插件本文以 PHP Simple
HTML DOM Parser 为例, 进行简单介绍, simple_html_dom 的语法类似 jQuery, 它让 php 操作 dom, 就像使用 jQuery 操作 dom 一样的 简单。 <?php $url='t.qq'; include_once('……/simplehtmldom/simple_html_dom.php'); $html=file_get_html($url); $title=$html->find('title'); echo $title[0]->plaintext; ?>