PHP: How to read a text file line by line

Had to read a file line by line in php, without completely loading it in memory.
The file is way too big to open only in memory, so I was getting memory exhaust errors.

This can be solved by using fgets() function to read the file line by line:

$handle = fopen("myfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // the line read
    }
    fclose($handle);
} else {
    // open file error
}

Did this worked out for you? Post your comments below.

Exit mobile version