file_get_contents函式不能使用的解決方法
日期:2008-06-20 作者:喜騰小二 來源:PHPChina
有些主機服務商把php的allow_url_fopen選項是關閉了,就是沒法直接使用file_get_contents來獲取遠端web页面的內容。那就是可以使用另外一個函式curl。
下麵是file_get_contents和curl兩個函式同樣功能的不同寫法
file_get_contents函式的使用範例:
< ?php
$file_contents = file_get_contents('http://www.ccvita.com/');
echo $file_contents;
?>
換成curl函式的使用範例:
< ?php
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'http://www.ccvita.com');
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函式來判斷php是否支援一個函式可以輕鬆寫出下麵函式
< ?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;
}
?>
其實上麵的這個函式還有待商榷,如果妳的主機服務商把file_get_contents和curl都關閉了,上麵的函式就會出現錯誤。
<<<返回技術中心