比file_get_contents穩(wěn)定的curl_get_contents分享
更新時間:2012年01月11日 21:47:21 作者:
相信使用過file_get_contents函數(shù)的朋友都知道,當(dāng)獲取的$url訪問不了時,會導(dǎo)致頁面漫長的等待,甚至還能導(dǎo)致PHP進程占用CPU達100%,因此這個函數(shù)就誕生了
分享一個實際在用的函數(shù):
/*比file_get_contents穩(wěn)定的多!$timeout為超時時間,單位是秒,默認(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.dbjr.com.cn');
相信使用過file_get_contents函數(shù)的朋友都知道,當(dāng)獲取的$url訪問不了時,會導(dǎo)致頁面漫長的等待,甚至還能導(dǎo)致PHP進程占用CPU達100%,因此這個函數(shù)就誕生了。curl的一些常識介紹
保留原file_get_contents函數(shù)的原因是當(dāng)讀取本地文件時,用原生的file_get_contents顯然更合適。
另來自張宴的file_get_contnets的優(yōu)化,具體可看:http://www.dbjr.com.cn/article/28030.htm
同樣是設(shè)置超時時間來解決這個問題。如果沒裝curl,就必須得用這個方式了。
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1 //設(shè)置一個超時時間,單位為秒
)
)
);
file_get_contents("http://www.dbjr.com.cn/", 0, $ctx);
另外,據(jù)不完全測試,使用curl獲取頁面比用file_get_contents穩(wěn)定的多。
復(fù)制代碼 代碼如下:
/*比file_get_contents穩(wěn)定的多!$timeout為超時時間,單位是秒,默認(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.dbjr.com.cn');
相信使用過file_get_contents函數(shù)的朋友都知道,當(dāng)獲取的$url訪問不了時,會導(dǎo)致頁面漫長的等待,甚至還能導(dǎo)致PHP進程占用CPU達100%,因此這個函數(shù)就誕生了。curl的一些常識介紹
保留原file_get_contents函數(shù)的原因是當(dāng)讀取本地文件時,用原生的file_get_contents顯然更合適。
另來自張宴的file_get_contnets的優(yōu)化,具體可看:http://www.dbjr.com.cn/article/28030.htm
同樣是設(shè)置超時時間來解決這個問題。如果沒裝curl,就必須得用這個方式了。
復(fù)制代碼 代碼如下:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1 //設(shè)置一個超時時間,單位為秒
)
)
);
file_get_contents("http://www.dbjr.com.cn/", 0, $ctx);
另外,據(jù)不完全測試,使用curl獲取頁面比用file_get_contents穩(wěn)定的多。
您可能感興趣的文章:
- php基于curl重寫file_get_contents函數(shù)實例
- PHP CURL或file_get_contents獲取網(wǎng)頁標(biāo)題的代碼及兩者效率的穩(wěn)定性問題
- php中file_get_contents與curl性能比較分析
- php采用file_get_contents代替使用curl實例
- 深入file_get_contents與curl函數(shù)的詳解
- 探討file_get_contents與curl效率及穩(wěn)定性的分析
- php中使用Curl、socket、file_get_contents三種方法POST提交數(shù)據(jù)
- PHP curl 或 file_get_contents 獲取需要授權(quán)頁面的方法
相關(guān)文章
PHP調(diào)用MySQL的存儲過程的實現(xiàn)代碼
MySQL好像從5.0開始才引入存儲過程,反正以前做應(yīng)用的時候從沒碰過,不過現(xiàn)在因為主要作內(nèi)部系統(tǒng)2008-08-08PHP預(yù)定義超全局?jǐn)?shù)組變量小結(jié)
這篇文章主要介紹了PHP預(yù)定義超全局?jǐn)?shù)組變量,結(jié)合實例形式總結(jié)分析了預(yù)定義超全局?jǐn)?shù)組變量的特性、功能、使用方法及相關(guān)操作注意事項,需要的朋友可以參考下2018-08-08