依您的需求量身訂做,提供投資型、保障型
退休型等多元化保險商品,專業有保障
招牌專業居家清潔
免費到府估價,清潔養護馬上搞定

首頁  •  j2h 論壇 • 程式設計討論     • 

[php] 如何使用PHP抓取網頁內容

房東:愛國者
發表時間:2012-01-12


在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();





  • 贊助網站       

    廣利不動產-板橋在地生根最實在--新板特區指名度最高、值得您信賴的好房仲
    完整房訊,房屋、店面熱門精選物件,廣利不動產 優質仲介,房屋租賃、買賣資訊透明,交易真安心!
    廣利不動產-新板特區指名度最高、值得您信賴的好房仲
    您的托付,廣利用心為您服務

  • 1 樓住戶:小老弟
    發表時間:2012-01-12

    $url = 'http://blog.xuite.net/coke750101/networkprogramming';
    $ch = curl_init(); //初始化
    $timeout = 30;
    $useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
    $cookie = "cookieLangId=zh_tw;";

    curl_setopt ($ch, CURLOPT_URL, $url); //設定抓取網址
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);//逾時時間
    curl_setopt ($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt ($ch, CURLOPT_COOKIE, $cookie);

    $data = curl_exec($ch); //抓取網頁

    curl_close($ch);
    $file = fopen("out.html", 'w'); //開啟檔案
    fwrite($file, $data); //寫入檔案
    fclose($file); //關閉檔案
    ?>




     共 1 人回應  選擇頁數 【第1 頁】 

    姓名:
    佈告內容:
    其他選項: