函數:stream_context_create ,file_get_content
創建並返回一個文本數據流並應用各種選項,可用於fopen(),file_get_contents()等過程的超時設置、代理服務器、請求方式、頭信息設置的特殊過程。
函數原型:resource stream_context_create ([ array $options [, array $params ]] )
在使用file_get_contents函數的時候,經常會出現超時的情況,在這里要通過查看一下錯誤提示,看看是哪種錯誤,比較常見的是讀取超時,這種情況大家可以通過一些方法來盡量的避免或者解決。這里就簡單介紹兩種:
注意: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://blog.sina.com/mirze', false, $context);
如果還有報錯可以使用 @ 禁止報錯符,如:@file_get_contents
示例:method 可以使用pos和get
function ip_taobao($ip){ $opt = [ 'http'=>[ 'method'=>'post', 'timeout'=> 2 ] ]; $context = stream_context_create($opt); $urlTaobao = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip; $json = @file_get_contents($urlTaobao,false,$context); $jsonDecode = json_decode($json); if($jsonDecode){ $data['country'] = $jsonDecode->data->country; $data['province'] = $jsonDecode->data->region; $data['city'] = $jsonDecode->data->city; $data['isp'] = $jsonDecode->data->isp; }else{ $data['country'] = '網絡已斷開'; } return $data; }
二、php代碼超時,再次發送請求
有時候失敗是因為網絡等因素造成,沒有解決辦法,但是可以修改程序,失敗時重試幾次,仍然失敗就放棄,因為file_get_contents()如果失敗將返回 FALSE,所以可以下面這樣編寫代碼:
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http://blog.sina.com/mirze'))===FALSE) $cnt++;