在php中file_get_contents與curl()函數都可以用來抓取對方網站的資料並儲存到本機伺服器中,但是總得來講file_get_contents()效率稍低些,常用失敗的情況、curl()效率挺高的,支援多線程,不過需要開啟下curl擴充,也就是說要使用curl函數就必須要開啟curl擴充了,而file_get_contents函數系統是預設的哦。
下面是curl擴充開啟的步驟:
1、將PHP檔案夾下的三個檔案php_curl.dll,libeay32.dll,ssleay32.dll複製到system32下;
2、將php.ini(c:WINDOWS目錄下)中的;extension=php_curl.dll中的分號去掉;
3、重啟apache或者IIS。
我們先來看看兩個函數的簡單一實例
curl()函數
| 代碼如下 |
複製代碼 |
$ch = curl_init("http://www.bKjia.c0m/"); curl_exec($ch); curl_close($ch); //$ch = curl_init("要採集的網址"); curl_init()函數的作用初始化一個curl會話 //curl_exec($ch);執行$ch //curl_close($ch); 關閉$ch |
file_get_contents函數
例子
| 代碼如下 |
複製代碼 |
echo file_get_contents("http://www.hzhuti.com"); ?> |
輸出:
| 代碼如下 |
複製代碼 |
This is a test file with test text. |
總結
fopen / file_get_contents 每次請求都會重新做DNS查詢,並不對DNS資訊進行緩衝。
但是CURL會自動對DNS資訊進行緩衝。對同一網域名稱下的網頁或者圖片的請求只需要一次DNS查詢。這大大減少了DNS查詢的次數。
所以CURL的效能比fopen / file_get_contents 好很多。
file_get_contents與curl效率及穩定性問題
| 代碼如下 |
複製代碼 |
$config['context'] = stream_context_create(array('http' => array('method' => "GET",'timeout' => 5)));
|
'timeout' => 5//這個逾時時間不穩定,經常不好使。這時候,看一下伺服器的串連池,會發現一堆類似下面的錯誤,讓你頭疼萬分:
| 代碼如下 |
複製代碼 |
| file_get_contents(http://***): failed to open stream… |
不得已,安裝了curl庫,寫了一個函數替換:
| 代碼如下 |
複製代碼 |
function curl_get_contents($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); //設定訪問的url地址 //curl_setopt($ch,CURLOPT_HEADER,1); //是否顯示頭部資訊 curl_setopt($ch, CURLOPT_TIMEOUT, 5); //設定逾時 curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_); //使用者訪問代理 User-Agent curl_setopt($ch, CURLOPT_REFERER,_REFERER_); //設定 referer curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); //跟蹤301 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回結果 $r = curl_exec($ch); curl_close($ch); return $r; } |
如此,除了真正的網路問題外,沒再出現任何問題。
這是別人做過的關於curl和file_get_contents的測試:
file_get_contents抓取google.com需用秒數:
| 代碼如下 |
複製代碼 |
1.2.31319094 2.2.30374217 3.2.21512604 4.3.30553889 5.2.30124092 curl使用的時間: 1.0.68719101 2.0.64675593 3.0.64326 4.0.81983113 5.0.63956594 |
那麼如何根據伺服器情況來使用file_get_contents還是curl()呢,下面我們可以利用function_exists函數來判斷php是否支援一個函數可以輕鬆寫出下面函數
| 代碼如下 |
複製代碼 |
< ?php function vita_get_url_content($url) { if(function_exists('file_get_contents')) { $file_contents = file_get_contents($url); } else { $ch = curl_init(); $timeout = 5; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $file_contents = curl_exec($ch); curl_close($ch); } return $file_contents; } ?> |
http://www.bkjia.com/PHPjc/633083.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/633083.htmlTechArticle在php中file_get_contents與curl()函數都可以用來抓取對方網站的資料並儲存到本機伺服器中,但是總得來講file_get_contents()效率稍低些,常用失敗...