Sometimes, we want to read a large file line by line in PHP.
In this article, we’ll look at how to read a large file line by line in PHP.
How to read a large file line by line in PHP?
To read a large file line by line in PHP, we call the fopen
function.
For instance, we write
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// ...
}
fclose($handle);
} else {
// ...
}
to call fopen
with the path to the file we want to read and the permission string.
'r'
stands for read.
Then we call fgets
with the $handle
to read the file and get the next $line
from the file.
We do that in the while loop header to read all the $line
s until $line
is false
.
Then we call fclose
to close the file.
If $handle
is false
, then the file can’t be read.
Conclusion
To read a large file line by line in PHP, we call the fopen
function.