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