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;
本文为原创文章,版权归国外主机测评所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ public function list()报错 syntax error, unexpected T_LIST, expecting T_STRING08/25
- ♥ 天平高的一面是德字低的一面是望字是什么成语?08/23
- ♥ 两个官字是什么成语?08/24
- ♥ Could not reliably determine the server's fully qualified domain name, using xxx for ServerName08/26
- ♥ 【疯狂猜成语/图猜成语】一只手抓着草是什么成语?08/20
- ♥ dedecms 删除标题重复的文章 dedecms 删除采集重复的数据08/31