-1

My goal is to get every line of text from text line number 10 to number 15.

text file :

enter image description here

my code :

$file = fopen('no_list.txt', 'r');
while ((feof ($file) === false) )
{
    $i=1;
    while ((feof ($file) === false) && $i<10 && $i<15 )
    {
        fgets($file);
        $i++;
    }
    $splitdata = fgets($file);
    echo $splitdata;
}
fclose($file);

The code only returns the data from line 15. Any suggestion what am I missing from my code? or any other solution to do it ?

mickmackusa
  • 33,121
  • 11
  • 58
  • 86
Tray Scott
  • 13
  • 4
  • For best efficiency, you would read `seek` to the first desired line, then if you are doing an loop, break your loop after you echo'ed your last desired line of text. – mickmackusa Oct 26 '20 at 23:20

2 Answers2

1

You could use file() to read your text file into an array and filter out the lines you need:

<?php

$lines = file('test.txt');
$start = 10;
$end = 15;

for($i = $start-1; $i<=$end-1; $i++) {
    $store[] = $lines[$i];
}

Array $store contains an element for each line that you selected to filter, in between $start and $end;

jibsteroos
  • 1,110
  • 2
  • 5
  • 9
0

Easier to read the file into an array and slice off what you want:

$splitdata = array_slice(file('no_list.txt'), 9, 6);

$splitdata will be an array so loop or implode it to echo:

echo implode(', ', $splitdata);
AbraCadaver
  • 73,820
  • 7
  • 55
  • 81