Home >Backend Development >PHP Tutorial >Summary of methods for getting the number of lines in a file in php

Summary of methods for getting the number of lines in a file in php

高洛峰
高洛峰Original
2016-12-20 15:43:391527browse

stream_get_line gets the number of file lines

<?php
$file_path = &#39;xxx.txt&#39;; //文件路径
$line = 0 ; //初始化行数
//打开文件
$fp = fopen($file_path , &#39;r&#39;) or die("open file failure!");
if($fp){
//获取文件的一行内容,注意:需要php5才支持该函数;
while(stream_get_line($fp,8192,"\n")){
 $line++;
}
fclose($fp);//关闭文件
}
//输出行数;
echo $line;
?>

feof and fgets get the number of file lines

<?php
$lines = 0;//初始化行数
 
if ($fh = fopen(&#39;data.txt&#39;,&#39;r&#39;)) {//打开文件
 while (! feof($fh)) {//判断是否已经达到文件底部
  if (fgets($fh)) {//读取一行内容
   $lines++;
  }
 }
}
print $lines;
?>

count gets the number of file lines

<?php
 $line = count(file(&#39;filename&#39;));
 echo $line;
?>

The third way is because To save the contents of a file, The efficiency will be very poor. The editor here recommends that you use the first and second methods.

Thanks for reading, I hope it can help everyone, thank you for your support of this site!

For more PHP methods to get the number of file lines and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn