做過好多抓取別家網站內容的產品,習慣了使用方便快捷的file_get_contents函數,但是總是會遇到獲取失敗的問題,盡管按照手冊中的例子設置了超時,可多數時候不會奏效:
復制代碼 代碼如下:
$config['context'] = stream_context_create(array(‘http' => array(‘method' => “GET”,
'timeout' => 5//這個超時時間不穩定,經常不奏效
)
));
這時候,看一下服務器的連接池,會發現一堆類似的錯誤,讓你頭疼萬分:
file_get_contents(http://***): failed to open stream…
不得已,安裝了curl庫,寫了一個函數替換:
復制代碼 代碼如下:
<span >function</span> curl_file_get_contents<span >(</span><span >$durl</span><span >)</span><span >{</span>
<span >$ch</span> <span >=</span> <span >curl_init</span><span >(</span><span >)</span><span >;</span>
<span >curl_setopt</span><span >(</span><span >$ch</span><span >,</span> CURLOPT_URL<span >,</span> <span >$durl</span><span >)</span><span >;</span>
<span >curl_setopt</span><span >(</span><span >$ch</span><span >,</span> CURLOPT_TIMEOUT<span >,</span> <span >5</span><span >)</span><span >;</span>
<span >curl_setopt</span><span >(</span><span >$ch</span><span >,</span> CURLOPT_USERAGENT<span >,</span> _USERAGENT_<span >)</span><span >;</span>
<span >curl_setopt</span><span >(</span><span >$ch</span><span >,</span> CURLOPT_REFERER<span >,</span>_REFERER_<span >)</span><span >;</span>
<span >curl_setopt</span><span >(</span><span >$ch</span><span >,</span> CURLOPT_RETURNTRANSFER<span >,</span> <span >1</span><span >)</span><span >;</span>
<span >$r</span> <span >=</span> <span >curl_exec</span><span >(</span><span >$ch</span><span >)</span><span >;</span>
<span >curl_close</span><span >(</span><span >$ch</span><span >)</span><span >;</span>
<span >return</span> <span >$r</span><span >;</span>
<span >}</span>
如此,除了真正的網絡問題外,沒再出現任何問題。
這是別人做過的關於curl和file_get_contents的測試:
file_get_contents抓取google.com需用秒數:
2.31319094
2.30374217
2.21512604
3.30553889
2.30124092
curl使用的時間:
0.68719101
0.64675593
0.64326
0.81983113
0.63956594
差距很大吧?呵呵,從我使用的經驗來說,這兩個工具不只是速度有差異,穩定性也相差很大。建議對網絡數據抓取穩定性要求比較高的朋友使用上面的curl_file_get_contents函數,不但穩定速度快,還能假冒浏覽器欺騙目標地址哦!