PHP method to obtain the number of lines in a file

墨辰丷
Release: 2023-03-28 21:08:02
Original
3059 people have browsed it

This article introduces you to three ways to get the number of file lines in PHP. The first method is to use the feof and fgets functions, the second method is to use the stream_get_line function, and 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 = &#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; 
?>
Copy after login

feof and fgets to 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;
?>
Copy after login

count Get the number of file lines

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

The third method will be very inefficient because it needs to save the contents of the file. The editor here recommends that you use the first and second methods.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

phpHow to use html5 to upload multiple files

phpMethods to implement registration and login interface

phpRegistration and login interface implementation case

The above is the detailed content of PHP method to obtain the number of lines in a file. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!