|
下面是file_get_contents和curl兩個(gè)函數(shù)同樣功能的不同寫法
file_get_contents函數(shù)的使用示例:
復(fù)制代碼 代碼如下:
< ?php
$file_contents = file_get_contents('http://www.jb51.NET');
echo $file_contents;
?>
換成curl函數(shù)的使用示例:
復(fù)制代碼 代碼如下:
< ?php
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'http://www.jb51.NET');
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是否支持一個(gè)函數(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í)上面的這個(gè)函數(shù)還有待商榷,如果你的主機(jī)服務(wù)商把file_get_contents和curl都關(guān)閉了,上面的函數(shù)就會(huì)出現(xiàn)錯(cuò)誤。
php技術(shù):深入file_get_contents與curl函數(shù)的詳解,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。