Home > Article > Backend Development > Detailed example of how to get the number of lines in a file in php
This article introduces you to three ways to get the number of file lines in PHP. The first method is to use feof and fgets function, and the second method is to use the stream_get_line function. The third method is to use the count function. For specific implementation, please see the example below
stream_get_line to get the number of file lines
<?php $file_path = 'xxx.txt'; //文件路径 $line = 0 ; //初始化行数 //打开文件 $fp = fopen($file_path , 'r') or die("open file failure!"); if($fp){ //获取文件的一行内容,注意:需要php5才支持该函数; while(stream_get_line($fp,8192,"\n")){ $line++; } fclose($fp);//关闭文件 } //输出行数; echo $line; ?>
feof and fgets gets the number of file lines
<?php $lines = 0;//初始化行数 if ($fh = fopen('data.txt','r')) {//打开文件 while (! feof($fh)) {//判断是否已经达到文件底部 if (fgets($fh)) {//读取一行内容 $lines++; } } } print $lines; ?>
count gets the number of file lines
<?php $line = count(file('filename')); echo $line; ?>
The third method is very inefficient because it needs to save the content of the file. The editor here recommends that you use the first and second methods.
The above is the detailed content of Detailed example of how to get the number of lines in a file in php. For more information, please follow other related articles on the PHP Chinese website!