There is a file with the nth number of lines. It is necessary to read lines using PHP, for example, from the 40th to the 80th.

I found a similar solution on the network, but it works like this: I indicate how many lines from the beginning should be skipped, and all the others are read ... this is a little different ... can anyone help modify the code so that you can specify the starting and ending lines? Here is the code itself:

<?php final class FileReader { protected $handler = null; protected $fbuffer = ""; /** * Конструктор класса, открывающий файл для работы * * @param string $filename */ public function __construct($filename) { if(!($this->handler = fopen($filename, "rb"))) throw new Exception("Cannot open the file"); } /** * Построчное чтение всего файла с учетом сдвига * * @return string */ public function ReadAll() { if(!$this->handler) throw new Exception("Invalid file pointer"); while(!feof($this->handler)) $this->fbuffer .= fgets($this->handler); return $this->fbuffer; } /** * Установить строку, с которой производить чтение файла * * @param int $line */ public function SetOffset($line) { if(!$this->handler) throw new Exception("Invalid file pointer"); while(!feof($this->handler) && $line--) { fgets($this->handler); } } }; /** * Пример использования */ $stream = new FileReader("lines.txt"); // Укажем, что читать надо с 20-ой строки $stream->SetOffset(20); // Получаем содержимое echo $stream->ReadAll(); /** * Количество прочитанных строк можно узнать так: * * echo count(explode("\n", $stream->ReadAll())); */ ?> 

I would be very grateful for the help!

    1 answer 1

    Rewrite readAll so

     public function ReadLines($start, $stop) { $count = $stop-$start+1; $start = $start - 1; while(!feof($this->handler) && $start--) { fgets($this->handler); } if(!$this->handler) throw new Exception("Invalid file pointer"); $this->fbuffer = ""; while(!feof($this->handler) && $count--) { $this->fbuffer .= fgets($this->handler); } return $this->fbuffer; } 

    and call so

     echo $stream->ReadLines(20,40); 

    reads from 20 to 40 inclusive.

    The code was written right here, so it's best to check for errors.

    • Yes constructive remark - Naumov
    • And why is the handler checked after use? - Naumov
    • @Naumov why is there to check it at all if it’s already done in the constructor? - Jean-Claude