首先解決file_get_contents的超時問題,在超時返回錯誤後就象js中的settimeout那樣進行一次嘗試,錯誤超過3次或者5次後就確認為無法連線伺服器而徹底放棄。
這裡就簡單介紹兩種解決方法:
一、增加超時的時間限制
注意:set_time_limit只是設定你的php程式的超時時間,而不是file_get_contents函數讀取url的超時時間。
我一開始以為set_time_limit也能影響到file_get_contents,後來經測試是無效的。真正的修改file_get_contents延時可以用resource $context的timeout參數:
php程式碼
$opts = array(
'http'=>array(
'method'=>"get",
'timeout'=>60,
)
);
$context = stream_context_create($opts);
$html =file_get_contents('http://www.example.com', false, $context);
fpassthru($fp);
二、多次嘗試
php程式碼
$cnt=0;
while($cnt $cnt++;
}
以上方法對付超時已經ok了。接下來演示一下用file_get_contents實現post,如下:
php程式碼
function post($url, $post = null){
$context = array();
if (is_array($post)) {
ksort($post);
$context['http'] = array (
'timeout'=>60,
'method' => 'post',
'content' => http_build_query($post, '', '&'),
);
}
return file_get_contents($url, false, stream_context_create($context));
}
$data = array (
'name' => 'test',
'email' => 'test@gmail.com',
'submit' => 'submit',
);
echo post('http://www.example.com', $data);
注意檔案頭的set_time_out否則整個檔案都得超時了
file_get_contents — 将整个文件读入一个字符串
说明
string file_get_contents ( string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen ]]]] )
和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败,file_get_contents() 将返回 FALSE。
file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。
Note: 如果要打开有特殊字符的 URL (比如说有空格),就需要使用 urlencode() 进行 URL 编码。
Note: context 参数可以用 NULL 来忽略。
file_get_contents() 读取一个文件中的内容,包括远程文件!!
file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法!!
echo file_get_contents('www.baidu.com');
?>
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号