Skipping lines using file_get_contents?

7.4k Views Asked by At

I'm trying to skip the first 2 lines (from reading 3 files) then save back (I already got this done, all that's left is the line skipping)

Is there any way to do this?

4

There are 4 best solutions below

1
On BEST ANSWER

This is one way of doing it. Perhaps it's a bit overkill, as it's not very efficient. (using file() would be much faster)

$content = file_get_contents($filename);
$lines = explode("\n", $content);
$skipped_content = implode("\n", array_slice($lines, 2));
2
On

Yes, but using file_get_contents it would be too complicated. I advise using the file() function instead:

$file_array = file("yourfile.txt");
unset($file_array[0]);
unset($file_array[1]);
file_put_contents("outfile.txt", implode("", $file_array));
0
On

use file(), then unset the the first 2 array keys then implode

0
On

If lines are not very long can't you just use regex on read files? From php manual there is offset parameter in file_get_contents, though this most likely wont be useful since then you need to know line lengths in advance. Maybe file_get_contents isn't proper function to use in this case?