php函数fgets读取文件

如果一个文件比较大,可以考虑用fgets函数

下面是个例子:

#文件作用:fgets读取文件
                                                                                                                          
$start_time = microtime(true);
$file_name = "a.txt";
$handle = fopen($file_name,'r');
$i = 0;
if($handle)
{
    while (!feof($handle)) {
        $line = fgets($handle);
        $line = str_replace("\n","",$line);
    }
}
 
$end_time =  microtime(true);
echo "程序耗时:".round($end_time-$start_time,3)."秒\n";

fgets() 从 handle 指向的文件中读取一行并返回长度最多为 length-1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length-1 字节后停止。如果没有指定 length ,则默认为 1K ,或者说 1024 字节。

补充说明

feof() 函数测试文件指针是否到了文件结束的位置,该文件指针必须有效,如果是无效的资源,则会陷入无限循环中。参见《PHP 文件指针函数

posted @ 2015-11-01 22:42  KoMiles  阅读(2206)  评论(0编辑  收藏  举报