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:
line one
line two
line three
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.
$lines = file('test.txt');
// Loop through our array
foreach ($lines as $line) {
var_dump($line);
}
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.
/test.php:6:
string(9) "line one
"
/test.php:6:
string(9) "line two
"
/test.php:6:
string(11) "line three
"
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.
$handle = fopen("./test.txt", "r");
if ($handle) {
while (($buffer = fgets($handle)) !== false) {
$text = rtrim($buffer);
var_dump($text);
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
Output:
/test.php:7:
string(8) "line one"
/test.php:7:
string(8) "line two"
/test.php:7:
string(10) "line three"
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.
$file = new SplFileObject("test.txt");
$file->setFlags(SplFileObject::DROP_NEW_LINE);
// Loop until we reach the end of the file.
while (!$file->eof()) {
// Echo one line from the file.
var_dump($file->fgets());
}
// Unset the file to call __destruct(), closing the file handle.
$file = null;
Output:
/test.php:8:
string(8) "line one"
/test.php:8:
string(8) "line two"
/test.php:8:
string(10) "line three"