php抓取頁面方法匯總

jopen 11年前發布 | 64K 次閱讀 PHP PHP開發

在做一些互聯網應用的時候,往往需要抓取網絡文件大多數網頁文件,一般情況下都是利用php模擬瀏覽器的訪問,通過http請求訪問url地址,然后得到html源代碼或者其它格式的數據,然后對這些數據進行處理格式化,按照我們事先約定好的方式輸出到終端或其它接口。

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

1. file()函數 

2. file_get_contents()函數 

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

4.curl方式 

5. fsockopen()函數 socket模式 

6. 使用插件(如:http://sourceforge.net/projects/snoopy/) 

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

1. 正則表達式 

2. PHP DOMDocument對象 

3. 插件(如:PHP Simple HTML DOM Parser) 

如果你對以上內容已經很了解,以下內容可以飄過...... 

PHP抓取頁面 

1. file()函數 

代碼如下:

<?php 

$url='http://t.qq.com'; 

$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='http://t.qq.com'; 

$lines_string=file_get_contents($url); 

echo htmlspecialchars($lines_string); 

?> 

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

代碼如下:

<?php 

$url='http://t.qq.com'; 

$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='http://t.qq.com'; 

$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); 

} 

?> 

6. 插件 

網上應該有比較多的插件,snoopy插件是在網上搜到的,有興趣的可以研究一下。 

PHP解析xml(html) 

1. 正則表達式: 

代碼如下:

<?php 

$url='http://t.qq.com'; 

$lines_string=file_get_contents($url); 

eregi('<title>(.*)</title>',$lines_string,$title); 

echo htmlspecialchars($title[0]); 

?> 

2. PHP DOMDocument()對象 

如果遠程的html或xml存在語法錯誤,php在解析dom的時候會報錯。 

代碼如下:

<?php 

$url='http://www.136web.cn'; 

$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='http://t.qq.com'; 

include_once('../simplehtmldom/simple_html_dom.php'); 

$html=file_get_html($url); 

$title=$html->find('title'); 

echo $title[0]->plaintext; 
?> 
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!