深入file_get_contents與curl函數(shù)的詳解
更新時間:2013年06月25日 18:03:42 作者:
本篇文章是對file_get_contents與curl函數(shù)進行了詳細的分析介紹,需要的朋友參考下
有些主機服務(wù)商把php的allow_url_fopen選項是關(guān)閉了,就是沒法直接使用file_get_contents來獲取遠程web頁面的內(nèi)容。那就是可以使用另外一個函數(shù)curl。
下面是file_get_contents和curl兩個函數(shù)同樣功能的不同寫法
file_get_contents函數(shù)的使用示例:
< ?php
$file_contents = file_get_contents('http://www.dbjr.com.cn');
echo $file_contents;
?>
換成curl函數(shù)的使用示例:
< ?php
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'http://www.dbjr.com.cn');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?>
利用function_exists函數(shù)來判斷php是否支持一個函數(shù)可以輕松寫出下面函數(shù)
< ?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;
}
?>
其實上面的這個函數(shù)還有待商榷,如果你的主機服務(wù)商把file_get_contents和curl都關(guān)閉了,上面的函數(shù)就會出現(xiàn)錯誤。
下面是file_get_contents和curl兩個函數(shù)同樣功能的不同寫法
file_get_contents函數(shù)的使用示例:
復(fù)制代碼 代碼如下:
< ?php
$file_contents = file_get_contents('http://www.dbjr.com.cn');
echo $file_contents;
?>
換成curl函數(shù)的使用示例:
復(fù)制代碼 代碼如下:
< ?php
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'http://www.dbjr.com.cn');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?>
利用function_exists函數(shù)來判斷php是否支持一個函數(shù)可以輕松寫出下面函數(shù)
復(fù)制代碼 代碼如下:
< ?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;
}
?>
其實上面的這個函數(shù)還有待商榷,如果你的主機服務(wù)商把file_get_contents和curl都關(guān)閉了,上面的函數(shù)就會出現(xià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效率及穩(wěn)定性的分析
- 比file_get_contents穩(wěn)定的curl_get_contents分享
- php中使用Curl、socket、file_get_contents三種方法POST提交數(shù)據(jù)
- PHP curl 或 file_get_contents 獲取需要授權(quán)頁面的方法
相關(guān)文章
PHP下利用header()函數(shù)設(shè)置瀏覽器緩存的代碼
PHP高級應(yīng)用學(xué)習(xí)筆記之 利用header()函數(shù)設(shè)置瀏覽器緩存2010-09-09PHP通過內(nèi)置函數(shù)memory_get_usage()獲取內(nèi)存使用情況
這篇文章主要介紹了PHP通過內(nèi)置函數(shù)memory_get_usage()獲取內(nèi)存使用情況,需要的朋友可以參考下2014-11-11