在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.companysz.com/");
- curl_exec($ch);
- curl_close($ch);
- //$ch = curl_init("要采集的網址"); curl_init()函數的作用初始化一個curl會話
- //curl_exec($ch);執行$ch
- //curl_close($ch); 關閉$ch
file_get_contents函數,代碼如下:
- <?php
- echo file_get_contents("http://www.companysz.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;
- }
- ?>
新聞熱點
疑難解答