If loading the entire file into memory is possible, you can do:
$file = file($filename);
$file = array_slice($file,0,20);
file_put_contents($filename,implode("",$file));
A better solution would be to use the ftruncate function , which takes a file descriptor and a new file size in bytes as follows:
$handle = fopen($filename, 'r+');
if(!$handle) {
}
$length = 0;
$count = 0;
while (($buffer = fgets($handle)) !== false) {
++$count;
if($count > 20) {
break;
}
$length += strlen($buffer);
}
ftruncate($handle, $length);
fclose($handle);
source
share