How to read large files in LIMITED memory in php

  • 2020-06-23 00:06:48
  • OfStack

Under normal circumstances, we can use fseek to read, the advantage is that it will not be a one-time read, the following code is only suitable for the case of side fetch processing, not the case of the first read one-time processing.
You can generate test files in the following ways

$file_handle = fopen("./csdn.txt", "rb+");
for ($index1 = 1; $index1 <= 2000000; $index1++) {
    fwrite($file_handle, 'http://ofstack.com'.$index1."\r");
}
fclose($file_handle);

The read processing code is as follows:

$i = 0;
$now = '';
while ($i >= 0) {
    if ($i>10) {
        break;
    }
    fseek($file_handle, 0, SEEK_CUR);
    $now = fgetc($file_handle);// You can make your own judgment false Head of presentation file 
    if ($now == "\r") {
        echo ' Find the breakpoint ';
    }
    echo $now;
    $i++;
}
fclose($file_handle);

Related articles: