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.

Download Code

 
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.

Download Code

 
The fgets() function is overloaded to read the file chunk by chunk to the desired length. This would translate to the simple code below:

Download Code

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.

Download Code

 
Alternatively, you can simply loop until you reach the end of the file. A simple foreach loop can be used to accomplish this.

Download Code

That’s all there is to reading a file line by line in PHP.