How to Read File Line by Line in PHP: Simple Guide
In PHP, you can read a file line by line using the
fgets() function inside a loop after opening the file with fopen(). Alternatively, you can use file() to get all lines as an array and loop through it.Syntax
To read a file line by line, you first open the file with fopen(), then use fgets() inside a loop to read each line until the end of the file. Finally, close the file with fclose().
fopen(filename, mode): Opens the file. Mode 'r' means read-only.fgets(file_handle): Reads one line from the file.feof(file_handle): Checks if the end of the file is reached.fclose(file_handle): Closes the file.
php
<?php $file = fopen('example.txt', 'r'); while (!feof($file)) { $line = fgets($file); // process $line } fclose($file); ?>
Example
This example reads a file named example.txt line by line and prints each line with a line number.
php
<?php $file = fopen('example.txt', 'r'); if ($file) { $lineNumber = 1; while (($line = fgets($file)) !== false) { echo "Line {$lineNumber}: " . htmlspecialchars($line) . "<br>"; $lineNumber++; } fclose($file); } else { echo "Unable to open the file."; } ?>
Output
Line 1: Hello, this is line one.
Line 2: This is line two.
Line 3: And here is line three.
Common Pitfalls
Common mistakes include not checking if the file opened successfully, which can cause errors. Also, using feof() incorrectly can lead to reading the last line twice or reading empty lines.
Always check the return value of fopen() and use fgets() in the loop condition to avoid extra empty lines.
php
<?php // Wrong way: Using feof() alone can cause an extra empty line $file = fopen('example.txt', 'r'); while (!feof($file)) { $line = fgets($file); echo $line; // May print an extra empty line } fclose($file); // Right way: Use fgets() in the while condition $file = fopen('example.txt', 'r'); while (($line = fgets($file)) !== false) { echo $line; } fclose($file); ?>
Quick Reference
- fopen(filename, 'r'): Open file for reading.
- fgets(file_handle): Read one line from file.
- feof(file_handle): Check end of file.
- fclose(file_handle): Close the file.
- file(filename): Read entire file into an array of lines.
Key Takeaways
Use fopen() with 'r' mode and fgets() inside a loop to read a file line by line.
Always check if fopen() succeeds before reading the file.
Use fgets() in the loop condition to avoid reading extra empty lines.
Close the file with fclose() after finishing reading.
file() function can read all lines into an array for simpler line-by-line processing.