Reads the content of a text file line by line in PHP
Here are several ways to read a text file line by line in PHP. Suppose there is a text file which contains three lines, per line like below:
1. With file method
file() methods will return the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached.
For a small file, this method is the most convenient. But sometimes we need to read large files, such as 100M, 1G, etc., which may cause memory limitations.
The output is as follows, you can see that there is a newline at the end of each line. We can use rtrim($line)
to strip trailing newline.
2. With fgets method
fgets($handle, $length) method will get line from file pointer. If we use fgets()
without $length
parameter, it will return a line.
Output:
3. With SplFileObject
We can use an object oriented interface class for a file - SplFileObject. fgets() will get line from file. We can add $file->setFlags(SplFileObject::DROP_NEW_LINE)
, in order to drop newlines at the end of a line.
Output: