If you want to count the number of lines in a text file, you can get it using some simple PHP code. All you have to do is, open the file, read it line by line and use php string function fgets() with a counter. See the below code:
In the above code, "input.txt" file is opened and $fp is the file pointer. It uses
fgets() function in a loop and counts each line untill end of file is reached. Finally, it prints the counter.
Let us see how we can write a simple program to count number of lines in a file and print the output in the browser. I have written php code to count lines in
index.php and kept them in a folder named 'line_count' under xampp/htdocs. See below:
input.txt is the input text file, number of lines of which we are going to count. Below is content of the file:
Input text file (input.txt)
PHP code to count number of lines in a text file (index.php)
It opens the file input.txt in read mode using
fopen() PHP function. Using a while loop, it reads each line of the file using
fgets() function and increments the counter. This is done till end of file is reached. After exiting from while loop, it closes the input file using
fclose() function. At the end, it displays the count.
Let us now test it.