我们在开发网络程序时,往往需要抓取非本地文件,一般情况下都是利用php模拟浏览器的访问,通过http请求访问url地址, 然后得到html源代码或者xml数据,得到数据我们不能直接输出,往往需要对内容进行提取,然后再进行格式化,以更加友好的方式显现出来。
一、 PHP抓取页面的主要方法:
立即学习“PHP免费学习笔记(深入)”;
二、PHP解析html或xml代码主要方式:
1. file()函数
<?php
//定义url
$url='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都不能打开远程文件。
<?php //定义url $url='http://t.qq.com'; //file_get_contents函数远程读取数据 $lines_string=file_get_contents($url); //输出内容,嘿嘿,大家也可以保存在自己的服务器上 echo htmlspecialchars($lines_string);
3. fopen()->fread()->fclose()模式
<?php
//定义url
$url='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句柄,释放资源
fclose($handle);
//输出内容,嘿嘿,大家也可以保存在自己的服务器上
echo $lines_string;
4. curl方式
使用curl必须空间开启curl。方法:windows下修改php.ini,将extension=php_curl.dll前面的分号去掉,而且需
要拷贝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安装curl扩展。
<?php // 创建一个新cURL资源 $url='http://t.qq.com'; $ch=curl_init(); $timeout=5; // 设置URL和相应的选项 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // 抓取URL $lines_string=curl_exec($ch); // 关闭cURL资源,并且释放系统资源 curl_close($ch); //输出内容,嘿嘿,大家也可以保存在自己的服务器上 echo $lines_string;
5. fsockopen()函数 socket模式
socket模式能否正确执行,也跟服务器的设置有关系,具体可以通过phpinfo查看服务器开启了哪些通信协议。
<?php
$fp = fsockopen("t.qq.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: t.qq.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
6.
<?php
//引入snoopy的类文件
require('Snoopy.class.php');
//初始化snoopy类
$snoopy = new Snoopy;
$url = "http://t.qq.com";
//开始采集内容
$snoopy->fetch($url);
//保存采集内容到$lines_string
$lines_string = $snoopy->results;
//输出内容,嘿嘿,大家也可以保存在自己的服务器上
echo $lines_string;
说明:设置agent是在 Snoopy.class.php 文件的第45行,请在该文件中搜索 “var $agent” (引号中的内容)。浏览器内容你可以使用PHP来获得,
使用 echo $_SERVER['HTTP_USER_AGENT']; 可以得到浏览器信息,将echo出来的内容复制到agent里面就可以了。
浪风小园子 -- 比较认真的PHP平台开发
本页完整页面地址:http://www.cnblogs.com/rirber/archive/2013/06/15/php-server-get-curl-data.html
本页网址缩短(url地址):http://url.cn/EeOhAy











