PHP快速获取文件行数
转自:https://www.cnblogs.com/quixon/p/4684898.html
提供两种实现方法,但是第一种效率最好
第一种:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php$file_path= 'test.txt'; //文件路径  此处找一个1094644行的TXT文件 test.txt$line= 0 ; //初始化行数//打开文件set_time_limit(0);echo"开始时间:".date("H:i:s")."</br>";  //此处设一个计时器 开始时间$fp= fopen($file_path, 'r') ordie("open file failure!");if($fp){//获取文件的一行内容,注意:需要php5才支持该函数;while(stream_get_line($fp,8192,"\n")){   $line++;}fclose($fp);//关闭文件}//输出行数;echo$line."</br>";echo"结束时间:".date("H:i:s")."</br>";  //此处设一个计时器 结束时间?> | 
查看一下网页显示结果:

连一秒都不到。可以看出这样的效率还是蛮高的。
第二种:
| 1 2 3 4 5 6 7 8 9 10 | <?php    $file_path= 'test.txt'; //文件路径  此处找一个1094644行的TXT文件 test.txt    set_time_limit(0);    echo"开始时间:".date("H:i:s")."</br>";  //此处设一个计时器 开始时间    $line= count(file($file_path));    //输出行数;    echo$line."</br>";    echo"结束时间:".date("H:i:s")."</br>";  //此处设一个计时器 结束时间?> | 
查看一下网页显示结果:

好像也很快,也不到1秒钟。
下面我再用时间戳试一下:
修改一下PHP语句
第一种方法:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php$file_path= 'test.txt'; //文件路径  此处找一个1094644行的TXT文件 test.txt$line= 0 ; //初始化行数//打开文件set_time_limit(0);$start_time=microtime(true);//获取程序执行开始的时间$fp= fopen($file_path, 'r') ordie("open file failure!");if($fp){//获取文件的一行内容,注意:需要php5才支持该函数;while(stream_get_line($fp,8192,"\n")){   $line++;}fclose($fp);//关闭文件}//输出行数;echo$line."</br>";$end_time=microtime(true);//获取程序执行结束的时间$elapse=$end_time-$start_time; //获取差值echo"消耗时间".$elapse."</br>";  //此处设一个计时器 结束时间?> | 
得到结果:

第二种方法:
| 1 2 3 4 5 6 7 8 9 10 11 12 | <?php    $file_path= 'test.txt'; //文件路径  此处找一个1094644行的TXT文件 test.txt    set_time_limit(0);    $start_time=microtime(true);//获取程序执行开始的时间    $line= count(file($file_path));    //输出行数;    echo$line."</br>";    $end_time=microtime(true);//获取程序执行结束的时间    $elapse=$end_time-$start_time; //获取差值    echo"消耗时间".$elapse."</br>";  //此处设一个计时器 结束时间?> | 
得到结果:

这种方法测试的可以明显看出来,还是第一种方法要好的多。
    博  主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/articles/11030973.html
 
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
    
地 址 :https://www.cnblogs.com/xiaqiuchu/articles/11030973.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号