PHP code to read and display a text file line by line

If you have a text file and want to read it line by line, you can use the fgets function. This can be useful even if you have a very large files.

1
2
3
4
5
6
$handle = fopen($filename, 'r');
while (!feof($handle)) {
        $buffer = fgets($handle);
        echo $buffer;
        echo '<br />';
    }

Alternatively you can output the file to an array first and display it one at a time. This method is not suitable for a large file.

1
2
3
4
5
6
7
8
$file_array = file($filename);
foreach ($file_array as $line_numbers=>$line)
{
 echo $line_numbers+1; //add 1 because array numbers start with 0
 echo '. ';
 echo $line;
 echo '<br />';
}

Leave a Reply

Your email address will not be published. Required fields are marked *