我們在開發(fā)網(wǎng)絡程序時,往往需要抓取非本地文件,一般情況下都是利用php模擬瀏覽器的訪問,通過http請求訪問url地址, 然后得到html源代碼或者xml數(shù)據(jù),得到數(shù)據(jù)我們不能直接輸出,往往需要對內(nèi)容進行提取,然后再進行格式化,以更加友好的方式顯現(xiàn)出來。
下面簡單說一下php抓取頁面的幾種方法及原理:
一、 PHP抓取頁面的主要方法:
- file()函數(shù)
- file_get_contents()函數(shù)
- fopen()->fread()->fclose()模式
- curl方式
- fsockopen()函數(shù) socket模式
- 使用插件(如:http://sourceforge.net/projects/snoopy/)
二、PHP解析html或xml代碼主要方式:
file()函數(shù)
<?php
// 定義url
$url = 'http://t.qq.com';
// fiel函數(shù)讀取內(nèi)容數(shù)組
$lines_array = file($url);
// 拆分數(shù)組為字符串
$lines_string = implode('',$lines_array);
// 輸出內(nèi)容,嘿嘿,大家也可以保存在自己的服務器上
echo $lines_string;
** file_get_contents()函數(shù)**
使用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函數(shù)遠程讀取數(shù)據(jù)
$lines_string = file_get_contents($url);
//輸出內(nèi)容,嘿嘿,大家也可以保存在自己的服務器上
echo htmlspecialchars($lines_string);
fopen()->fread()->fclose()模式
<?php
//定義url
$url = 'http://t.qq.com';
//fopen以二進制方式打開
$handle = fopen($url,"rb");
//變量初始化
$lines_string = "";
//循環(huán)讀取數(shù)據(jù)
do{
$data = fread($handle,1024);
if(strlen($data)==0) {
break;
}
$lines_string .= $data;
}
while(true);
//關閉fopen句柄,釋放資源
fclose($handle);
//輸出內(nèi)容,嘿嘿,大家也可以保存在自己的服務器上
echo $lines_string;
curl方式
使用curl必須空間開啟curl。
方法:windows下修改php.ini,將extension=php_curl.dll前面的分號去掉,而且需 要拷貝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安裝curl擴展。
<?php
// 創(chuàng)建一個新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資源,并且釋放系統(tǒng)資源
curl_close($ch);
//輸出內(nèi)容,嘿嘿,大家也可以保存在自己的服務器上
echo $lines_string;
fsockopen()函數(shù) socket模式
socket模式能否正確執(zhí)行,也跟服務器的設置有關系,具體可以通過phpinfo查看服務器開啟了哪些通信協(xié)議。
<?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);
}
snoopy插件,最新版本是Snoopy-1.2.4.zip Last Update: 2013-05-30,推薦大家使用
使用網(wǎng)上非常流行的snoopy來進行采集,這是一個非常強大的采集插件,并且它的使用非常方便,你也可以在里面設置agent來模擬瀏覽器信息。
<?php
//引入snoopy的類文件
require('Snoopy.class.php');
//初始化snoopy類
$snoopy = new Snoopy;
$url = "http://t.qq.com";
//開始采集內(nèi)容
$snoopy->fetch($url);
//保存采集內(nèi)容到$lines_string
$lines_string = $snoopy->results;
//輸出內(nèi)容,嘿嘿,大家也可以保存在自己的服務器上
echo $lines_string;
說明:設置agent是在 Snoopy.class.php 文件的第45行,請在該文件中搜索 “var $agent” (引號中的內(nèi)容)。瀏覽器內(nèi)容你可以使用PHP來獲得,使用 echo $_SERVER['HTTP_USER_AGENT']; 可以得到瀏覽器信息,將echo出來的內(nèi)容復制到agent里面就可以了。