8

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?

hakre
  • 193,403
  • 52
  • 435
  • 836
newbie
  • 24,286
  • 80
  • 201
  • 301

2 Answers2

22

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

Barry
  • 3,303
  • 7
  • 23
  • 42
Pramendra Gupta
  • 14,667
  • 4
  • 33
  • 34
  • 1
    This buffer thing bugs me too. Will the buffer contain more than one line, and if so, how should we browse it ? I used roughly this code, but removed this `4096` argument. It also makes me wonder *what* would happen if a line is longer than those 4096 – Balmipour Aug 22 '17 at 15:17
  • 6
    @KonradGałęzowski @Balmipour just change `fgets($handle, 4096)` to `fgets($handle)`. PHP doc says about second `length` argument: *If no length is specified, it will keep reading from the stream until it reaches the end of the line*. Answer should be also edited because question is about *Reading line by line* – mikep Dec 05 '18 at 09:10
4

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