|
復(fù)制代碼 代碼如下:
/*比file_get_contents穩(wěn)定的多!$timeout為超時時間,單位是秒,默認為1s。*/
function curl_get_contents($url,$timeout=1) {
$curlHandle = curl_init();
curl_setopt( $curlHandle , CURLOPT_URL, $url );
curl_setopt( $curlHandle , CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curlHandle , CURLOPT_TIMEOUT, $timeout );
$result = curl_exec( $curlHandle );
curl_close( $curlHandle );
return $result;
}
$hx = curl_get_contents('http://www.jb51.NET');
相信使用過file_get_contents函數(shù)的朋友都知道,當獲取的$url訪問不了時,會導(dǎo)致頁面漫長的等待,甚至還能導(dǎo)致php進程占用CPU達100%,因此這個函數(shù)就誕生了。curl的一些常識介紹
保留原file_get_contents函數(shù)的原因是當讀取本地文件時,用原生的file_get_contents顯然更合適。
另來自張宴的file_get_contNETs的優(yōu)化,具體可看:http://www.jb51.NET/article/28030.htm
同樣是設(shè)置超時時間來解決這個問題。如果沒裝curl,就必須得用這個方式了。
復(fù)制代碼 代碼如下:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1 //設(shè)置一個超時時間,單位為秒
)
)
);
file_get_contents("http://www.jb51.NET/", 0, $ctx);
另外,據(jù)不完全測試,使用curl獲取頁面比用file_get_contents穩(wěn)定的多。
php技術(shù):比file_get_contents穩(wěn)定的curl_get_contents分享,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。