Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading huge file line by line in PHP

Tags:

php

In Java I use Scanner to read text file line by line, so memory usage will be very low, because only one line is in memory once. Is there similar method in PHP?

like image 681
newbie Avatar asked Jul 26 '11 12:07

newbie


People also ask

Which function is used to read PHP file line by line?

PHP Read Single Line - fgets() The fgets() function is used to read a single line from a file.

Which PHP function reads a single line from a file?

PHP fgets() Function $file = fopen("test. txt","r");

Which PHP function is used to open a file?

PHP fgets() Function The fgets function is used to read php files line by line. It has the following basic syntax.


2 Answers

use fseek, fgets

$handle = fopen("/tmp/uploadfile.txt", "r") or die("Couldn't get handle");
if ($handle) {
    while (!feof($handle)) {
        $line = fgets($handle);
        // Process line here..
    }
    fclose($handle);
}

Reading very large files in PHP

like image 193
Pramendra Gupta Avatar answered Oct 16 '22 03:10

Pramendra Gupta


fgets($fileHandle) is what you're looking for. You get the file handle using fopen("filename.txt", "r"), and close it with fclose($fileHandle).

like image 24
Rob Percival Avatar answered Oct 16 '22 03:10

Rob Percival