Skip to content

How to read a file line by line in php

You can use the fgets() function with combination of fopne() funciton to read the file line by line.

$filename = "inputfile.txt";
if (file_exists($filename) && is_readable ($filename)) {
$fileResource  = fopen($filename, "r");
if ($fileResource) {
    while (($line = fgets($fileResource)) !== false) {
      echo $line;
    }
    fclose($fileResource);
} 
}

Using PHP5 spl iterators, object oriented style.

$file = new SplFileObject("file.txt");
while (!$file->eof()) {
    echo $file->fgets();
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments