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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP file_get_contents 函数超时的几种解决方法相关的知识,希望对你有一定的参考价值。

参考技术A 这里就简单介绍两种:
一、增加超时的时间限制
这里需要注意: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++;

php file_get_contents函数分段读取大记事本或其它文本文件

当我们遇到文本文件体积很大时,比如超过几十M甚至几百M几G的大文件,用记事本或者其它编辑器打开往往不能成功,因为他们都需要把文件内容全部放到内存里面,这时就会发生内存溢出而打开错误,遇到这种情况我们可以使用PHP的文件读取函数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() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。

应用:

$str = $content=file_get_contents("2.sql",FALSE,NULL,1024*1024,1024);
echo $str;

如果针对较小文件只是希望分段读取并以此读完可以使用fread()函数

$fp=fopen(‘2.sql‘,‘r‘);
while (!feof($fp)){
$str.=fread($fp, filesize ($filename)/10);//每次读出文件10分之1
//进行处理
}

echo $str;

转载:http://www.zui88.com/blog/view-316.html






以上是关于PHP file_get_contents 函数超时的几种解决方法的主要内容,如果未能解决你的问题,请参考以下文章

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

php file_get_contents函数分段读取大记事本或其它文本文件

PHP使用file_get_contents函数POST数据

php如何获取文件内容?

PHP 函数和@functions

file_get_contents()函数