|
定義和用法
file_get_contents() 函數(shù)把整個(gè)文件讀入一個(gè)字符串中。
和 file() 一樣,不同的是 file_get_contents() 把文件讀入一個(gè)字符串。
file_get_contents() 函數(shù)是用于將文件的內(nèi)容讀入到一個(gè)字符串中的首選方法。如果操作系統(tǒng)支持,還會(huì)使用內(nèi)存映射技術(shù)來增強(qiáng)性能。
語(yǔ)法
file_get_contents(path,include_path,context,start,max_length)參數(shù) 描述
path 必需。規(guī)定要讀取的文件。
include_path 可選。如果也想在 include_path 中搜尋文件的話,可以將該參數(shù)設(shè)為 "1"。
context 可選。規(guī)定文件句柄的環(huán)境。
context 是一套可以修改流的行為的選項(xiàng)。若使用 null,則忽略。
start 可選。規(guī)定在文件中開始讀取的位置。該參數(shù)是 php 5.1 新加的。
max_length 可選。規(guī)定讀取的字節(jié)數(shù)。該參數(shù)是 php 5.1 新加的。
說明
對(duì) context 的支持是 php 5.0.0 添加的。
針對(duì)超時(shí)或頁(yè)面過慢,一般可采取兩個(gè)解決方案:
一. 利用file_get_contents()第三個(gè)參數(shù)
復(fù)制代碼 代碼如下:
$url = "http://zhoz.com/zhoz.php";
$ctx = stream_context_create(array(
‘http' => array(‘timeout' => 10)
)
);
$result = @file_get_contents($url, 0, $ctx);
if($result){
var_dump($result);
}else{
echo " Buffer is empty";
}
?>
此方法1,我經(jīng)測(cè)試在本地反映良好,但如果在外網(wǎng)測(cè)試(環(huán)境:中國(guó)→美國(guó)服務(wù)器間)基本都是超時(shí)的情況。
測(cè)試了TimeOut基本沒有用了,建議以下方式
二. 使用curl擴(kuò)展庫(kù)
復(fù)制代碼 代碼如下:
$url = "http://zhoz.com/zhoz.php";
try {
echo date(‘Y-m-d h:i:s');
echo "";
//$buffer = file_get_contents($url);
$buffer = zhoz_get_contents($url);
echo date(‘Y-m-d h:i:s');
if(emptyempty($buffer)) {
echo " Buffer is empty";
} else {
echo " Buffer is not empty";
}
} catch(Exception $e) {
echo "error ";
}
function zhoz_get_contents($url, $second = 5) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_TIMEOUT,$second);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>
綜述,根據(jù)系統(tǒng)環(huán)境來選擇到底應(yīng)用哪種方法:
復(fù)制代碼 代碼如下:
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;
}
?>
php技術(shù):執(zhí)行、獲取遠(yuǎn)程代碼返回:file_get_contents 超時(shí)處理的問題詳解,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。