php抓取頁面的幾種方法
在做一些天氣預報或者RSS訂閲的程序時,往往需要抓取非本地文件,一般情況下都是利用php模擬瀏覽器的訪問,通過http請求訪問url地址, 然後得到html源代碼或者xml數據,得到數據我們不能直接輸出,往往需要對內容進行提取,然後再進行格式化,以更加友好的方式顯現出來。下面梳理了php抓取頁面的幾種方法,供大家參考借鑑。
下面簡單説一下php抓取頁面的幾種方法及原理:
一、 PHP抓取頁面的主要方法:
1. file()函數
2. file_get_contents()函數
3. fopen()->fread()->fclose()模式
方式
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。方法:編輯,設置 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下修改,將extension=php_前面的.分號去掉,而且需 要拷貝和到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://", 13, $errno, $errstr);
if (!$fp) {
echo "ERROR: $errno - $errstr<br />"
} else {
fwrite($fp, "")
echo fread($fp, 26)
fclose($fp)
}