本文實(shí)例講述了PHP中file_get_contents高級(jí)用法,分享給大家供大家參考。具體分析如下:
首先解決file_get_contents的超時(shí)問(wèn)題,在超時(shí)返回錯(cuò)誤后就象js中的settimeout那樣進(jìn)行一次嘗試,錯(cuò)誤超過(guò)3次或者5次后就確認(rèn)為無(wú)法連線伺服器而徹底放棄。
這裡就簡(jiǎn)單介紹兩種解決方法:
一、增加超時(shí)的時(shí)間限制
注意:set_time_limit只是設(shè)定你的PHP程式的超時(shí)時(shí)間,而不是file_get_contents函數(shù)讀取URL的超時(shí)時(shí)間。
我一開(kāi)始以為set_time_limit也能影響到file_get_contents,后來(lái)經(jīng)測(cè)試是無(wú)效的。真正的修改file_get_contents延時(shí)可以用resource $context的timeout參數(shù):
PHP程序代碼如下:
?1234567891011 $opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60, ) ); $context = stream_context_create($opts); $html =file_get_contents('http://www.jb51.net', false, $context); fpassthru($fp);
二、多次嘗試
PHP程序代碼如下:
?1234 $cnt=0; while($cnt < 3 && (){ $cnt++; }
以上方法對(duì)付超時(shí)已經(jīng)OK了。接下來(lái)演示一下用file_get_contents實(shí)現(xiàn)Post,如下:
PHP程序代碼
?12345678910111213141516171819202122 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' => , 'submit' => 'submit', ); echo Post('http://www.jb51.net', $data);
注意文檔頭的Set_time_out否則整個(gè)文檔都得超時(shí)了。
希望本文所述對(duì)大家php程序設(shè)計(jì)的學(xué)習(xí)有所幫助。
更多信息請(qǐng)查看IT技術(shù)專欄