0

I have large text file that contain 800 K lines size 60 MB.I tried this code

$fileData = function() {
    $file = fopen('800K.txt','r');
    if (!$file)
        die('file does not exist or cannot be opened');
    while (($line = fgets($file)) !== false) {
        yield $line;
    }
    fclose($file);
};

foreach ($fileData() as $line) {
   echo $line.'<br>';
}

It really works : ).but con is it reads all line 800 K lines :( ....... it is possible convert into for loop , so it will be easy to selected line like

for ($i=1; $i<=10000; $i++){ 
$line=trim($lines[$i]); 
}



ANSWER :
$i=0;  //// start number
foreach ($fileData() as $line) {
   if($i==100) break;  ///// end number
   echo $line.'<br>';
   $i++; 
}

1 Answers1

-1

Edit:

This post has a few tests where they do this with larger files...

https://stackoverflow.com/a/31235307/2405805

$file = '../data/800k.txt';
$lines = file($file);
$rangeStart = 200000;
$rangeEnd = 300000;
$selection = array_slice($lines,$rangeStart,$rangeEnd);
echo json_encode($selection);

Or:

$file = '../data/800k.txt';
$rangeStart = 200000;
$rangeLength = 100000;
foreach (new LimitIterator($file, $rangeStart, $rangeLength) as $line) {
    array_push($lines,$line);
}
echo json_encode($lines);

Note, I'm not 100% with these methods if the item starts at 0 or 1, so it may be (200000, 300000) or (199999, 299999);