2009年10月19日 星期一

如何使用PHP抓取網頁內容

在PHP中可以使用檔案的操作方式來取得網頁

fopen->fread->fclose

打開網址,讀取檔案,關閉檔案

$handle = fopen ("http://www.example.com/", "rb");
$contents = "";
do {
$data = fread($handle, 1024);
if (strlen($data) == 0) {
break;
}
$contents .= $data;
} while(true);
fclose ($handle);

***************************************************************
也可透過curl來使用

$url = "http://www.example.com/";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); //需要使用者登入
curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD); //需要使用者密碼
$contents = curl_exec($ch);
curl_close($ch);


***************************************************************

file_get_contents

$url = "http://www.example.com/";
$contents = file_get_contents($url);
/***如果中文顯示有問題可以使用iconv函式轉換編碼***/
$getcontent = iconv("big5", "utf-8",file_get_contents($url));

**************************************************************
透過ob緩衝來取的文件本身的內容

session_start();
ob_start();
include('test.php');
contents = ob_get_contents();

沒有留言: