How do I open a file from line X to line Y in PHP?

后端 未结 7 1324
情书的邮戳
情书的邮戳 2020-11-29 13:09

The closest I\'ve seen in the PHP docs, is to fread() a given length, but that doesnt specify which line to start from. Any other suggestions?

7条回答
  •  [愿得一人]
    2020-11-29 14:06

    Unfortunately, in order to be able to read from line x to line y, you'd need to be able to detect line breaks... and you'd have to scan through the whole file. However, assuming you're not asking about this for performance reasons, you can get lines x to y with the following:

    $x = 10; //inclusive start line
    $y = 20; //inclusive end line
    $lines = file('myfile.txt');
    $my_important_lines = array_slice($lines, $x, $y);
    

    See: array_slice

提交回复
热议问题