php 中提供了专门的 file 函数来读取文件,通过 file 函数可以一次性获取一个 txt 文件的行数:
<?php $line = count(file($filepath)); echo $line; ?>
但是 file 函数不适用于大文件,执行缓慢并且会造成严重的内存问题。
网上还有一种通过 fopen 函数以及 while 逐行统计的代码,如下:
<?php line = 0 ; $fp = fopen($filepath , 'r') or die("open file failure!"); if($fp){ while(stream_get_line($fp,8192,"n")){ $line++; } fclose($fp); } echo $line; ?>
这种方法在读取大文件行数时,同样面临着效率太慢的问题。
经过实践,我们采用以下方法可以超高效率的读取 txt 大文件行数,并且内存占用也很低。
<?php function count_line($file){ $fp=fopen($file, "r"); $i=0; while(!feof($fp)) { //每次读取 2M if($data=fread($fp,1024*1024*2)){ //计算读取到的行数 $num=substr_count($data,"n"); $i+=$num; } } fclose($fp); return $i; } ?>
通过多行统计,每次读取 N 个字节,然后再统计读取的行数累加。
测试情况,文件大小 3.14 GB
第 1 次:line: 13214810 , time:56.2779 s;
第 2 次:line: 13214810 , time:49.6678 s;
本文为原创文章,版权归主机之家测评所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ Laravel 报错 Call to undefined function IlluminateEncryptionopenssl_cipher_iv_length()08/24
- ♥ 【疯狂猜成语/图猜成语】日历上三个日子是太阳剩下的都是冰块是什么成语?08/20
- ♥ Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode 错误的解决办法08/28
- ♥ 禁止 layer.msg()在回调时抖动08/28
- ♥ 1M 等于多少字节08/22
- ♥ 一堆数字 3 一堆数字 5 是什么成语?08/24