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();
}

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

DMCA.com Protection Status