Heim  >  Artikel  >  Backend-Entwicklung  >  PHP file_get_contents 函数超时的几种解决办法

PHP file_get_contents 函数超时的几种解决办法

WBOY
WBOYOriginal
2016-06-13 13:25:17961Durchsuche

PHP file_get_contents 函数超时的几种解决方法

?

在使用file_get_contents函数的时候,经常会出现超时的情况,在这里要通过查看一下错误提示,看看是哪种错误,比较常见的是读取超时,这种情况大家可以通过一些方法来尽量的避免或者解决。
这里就简单介绍两种:?
一、增加超时的时间限制?
这里需要注意:set_time_limit只是设置你的PHP程序的超时时间,而不是file_get_contents函数读取URL的超时时间。?
我一开始以为set_time_limit也能影响到file_get_contents,后来经测试,是无效的。真正的修改file_get_contents延时可以用resource $context的timeout参数: ?
$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); 
?

二、一次有延时的话那就多试几次?
有时候失败是因为网络等因素造成,没有解决办法,但是可以修改程序,失败时重试几次,仍然失败就放弃,因为file_get_contents()如果失败将返回 FALSE,所以可以下面这样编写代码: ?

$cnt=0; 
while($cnt < 3 && ($str=@file_get_contents('http…'))===FALSE) $cnt++; 
?

?

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn