Read a file line by line in PHP
This article demonstrates how to read a file line by line in PHP.
1. Using fgets() function
You can use the fgets() function to read a file line by line. A single call to fgets() will read from the stream until the end of the line has been reached. You can read the contents of a file by repeatedly invoking the fgets() function until the end of the file (EOF) is reached.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $file = '/path/to/directory/file.txt'; $handle = fopen($file, 'r'); if ($handle) { while (($line = fgets($handle)) !== false) { echo $line, PHP_EOL; } fclose($handle); } ?> |
The generator functions are available in PHP since version 5.5. You might want to write a generator function for this task that returns an object that can be iterated over, as demonstrated below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php $fileData = function($file) { $handle = fopen($file, 'r'); if ($handle) { while (($line = fgets($handle)) !== false) { yield $line; } fclose($handle); } }; $file = '/path/to/directory/file.txt'; foreach ($fileData($file) as $line) { echo $line; } ?> |
The fgets() function is overloaded to read the file chunk by chunk to the desired length. This would translate to the simple code below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $file = '/path/to/directory/file.txt'; $handle = fopen($file, 'r'); if ($handle) { while (($buffer = fgets($handle, 4096)) !== false) { echo $buffer; } fclose($handle); } ?> |
2. Using SplFileObject class
Another option is to use the SplFileObject class, which is an object-oriented interface for a file. The following solution uses the SplFileObject object to open the current file and iterates over its contents line by line. The solution uses SplFileObject::fgets() to echo the next line from the file.
|
1 2 3 4 5 6 7 8 9 |
<?php $file = '/path/to/directory/file.txt'; $fileObj = new SplFileObject($file); while (!$fileObj->eof()) { echo $fileObj->fgets(); } ?> |
Alternatively, you can simply loop until you reach the end of the file. A simple foreach loop can be used to accomplish this.
|
1 2 3 4 5 6 7 8 |
<?php $file = '/path/to/directory/file.txt'; $fileObj = new SplFileObject($file); foreach ($fileObj as $line) { echo $line; } ?> |
That’s all there is to reading a file line by line in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)