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 and read it line by line using the PHP string function fgets()
with a counter. See the below code:
<?php
$fp = fopen("input.txt", "r") or die("Unable to open file!");
// count lines
$line_count = 0;
while (!feof($fp)) { // loop until end of file
$line = fgets($fp);
++$line_count;
}
fclose($fp);
echo "No. of lines in the input file = ".$line_count;
In the above code, the "input.txt" file is opened and $fp is the file pointer. It uses fgets()
function in a loop and counts each line until the end of the file is reached. Finally, it prints the counter.
Let us see how we can write a simple PHP program to count the number of lines in a file and print the output in the browser. I have written a PHP program (index.php
) to count the lines in a text file. This program is kept in a folder named 'line_count' under xampp/htdocs.
"input.txt" is the input text file, we are going to count the number of lines of this file. Below is the content of the file:
Input text file (input.txt)
This is a test input file to count the number of lines in the file using PHP.
Using PHP open the file and count lines in a loop
Print the count after the loop as output
Close the input file
Count the number of lines in a text file (index.php)
<html>
<head>
<title>Count lines in a file</title>
</head>
<body style="text-align: center;font-size: 20px;">
<h1>Line count in a file</h1>
<?php
$fp = fopen("input.txt", "r") or die("Unable to open file!");
// count lines
$line_count = 0;
while (!feof($fp)) { // loop until end of file
$line = fgets($fp);
++$line_count;
}
fclose($fp);
echo "No. of lines in the input file = ".$line_count;
?>
</body>
</html>
It opens the file "input.txt" in read mode using the fopen()
function. Using a WHILE loop, it reads each line of the input file using fgets()
function and increments the counter. This is done till the end of the file is reached. After exiting from the WHILE loop, it closes the input file using fclose()
function. At the end, it displays the count.
Let us now test it.
Post a Comment