Home  >  Article  >  Backend Development  >  PHP code to count file lines

PHP code to count file lines

WBOY
WBOYOriginal
2016-07-25 08:56:51881browse
This article shares a PHP code for counting file lines. Instead of using the file() function, it uses a custom function and uses the fopen series of functions to achieve this function. I hope to be helpful.

In PHP, if you want to count the number of lines in a file, it is most convenient to use the file() function for small files. However, for large files, using the file() function will be very inefficient because this function will read the data into an array at one time and then store it in memory. Due to PHP memory limitations, this method is extremely inefficient and error-prone when processing large files.

The method introduced in this article can handle files of any size by traversing the file line by line without considering memory limitations.

The code for counting the number of lines in a file is as follows:

<?php
 /*** 统计文件行数,调用示例 ***/
 echo countLines("/path/to/file.txt");

 /**
 *
 * @统计文件行数
 * @param string filepath 
 * @return int
 * @edit bbs.it-home.org
 */
 function countLines($filepath) 
 {
    /*** open the file for reading ***/
    $handle = fopen( $filepath, "r" );
    /*** set a counter ***/
    $count = 0;
    /*** loop over the file ***/
    while( fgets($handle) ) 
    {
        /*** increment the counter ***/
        $count++;
    }
    /*** close the file ***/
    fclose($handle);
    /*** show the total ***/
    return $count;
 }

?>


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