1. 程式人生 > >PHP中獲取某個網頁或檔案內容的方法

PHP中獲取某個網頁或檔案內容的方法

1. 通過file_get_contents()函式 $contents = file_get_contents('http://demo.com/index.php'); echo $contents;
2. 通過fopen()和fread()函式 $handle = fopen('http://demo.com/index.php', 'r');    // 以只讀方式開啟檔案並將指標指向檔案頭,資源型別 $contents = ''; while (!feof($handle)){    // 判斷檔案指標是否到了檔案的末尾     $contents .= fread($handle, 1024);    // 每次讀取1024個位元組的資料 } fclose($handle);    // 關閉檔案 echo $contents; 3. 通過php的curl擴充套件庫
// 建立一個curl會話資源 $ch = curl_init(); // 設定curl相應的選項 curl_setopt($ch, CURLOPT_URL, "http://demo.com/index.php"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 執行curl $contents = curl_exec($ch); // 關閉curl會話 curl_close($ch); echo $contents; 總結: php中獲取檔案內容的方法有很多種,這裡只列舉了常用的三種,推薦使用第三種方法(curl抓取方式),curl是模擬瀏覽器的操作,效率比前兩種方法要高,而且支援很多選項設定,操作起來更加靈活。不足之處是,curl方式必須要有php的curl擴充套件庫的支援。