使用php删除前20行以外的所有行

时间:2010-12-10 14:57:41

标签: php file truncate lines

如何使用php从文本文件中删除除前20行之外的所有行?

5 个答案:

答案 0 :(得分:7)

如果将整个文件加载到内存中是可行的,您可以这样做:

// read the file in an array.
$file = file($filename);

// slice first 20 elements.
$file = array_slice($file,0,20);

// write back to file after joining.
file_put_contents($filename,implode("",$file));

更好的解决方案是使用函数ftruncate,它接受​​文件句柄和文件的新大小,如下所示:

// open the file in read-write mode.
$handle = fopen($filename, 'r+');
if(!$handle) {
    // die here.
}

// new length of the file.
$length = 0;

// line count.
$count = 0;

// read line by line.    
while (($buffer = fgets($handle)) !== false) {

        // increment line count.
        ++$count;

        // if count exceeds limit..break.
        if($count > 20) {
                break;
        }

        // add the current line length to final length.
        $length += strlen($buffer);
}

// truncate the file to new file length.
ftruncate($handle, $length);

// close the file.
fclose($handle);

答案 1 :(得分:5)

对于内存有效的解决方案,您可以使用

$file = new SplFileObject('/path/to/file.txt', 'a+');
$file->seek(19); // zero-based, hence 19 is line 20
$file->ftruncate($file->ftell());

答案 2 :(得分:0)

道歉,误读了这个问题......

$filename = "blah.txt";
$lines = file($filename);
$data = "";
for ($i = 0; $i < 20; $i++) {
    $data .= $lines[$i] . PHP_EOL;
}
file_put_contents($filename, $data);

答案 3 :(得分:0)

类似的东西:

$lines_array = file("yourFile.txt");
$new_output = "";

for ($i=0; $i<20; $i++){
$new_output .= $lines_array[$i];
}

file_put_contents("yourFile.txt", $new_output);

答案 4 :(得分:0)

这应该可以在没有大量内存使用的情况下使用

$result = '';
$file = fopen('/path/to/file.txt', 'r');
for ($i = 0; $i < 20; $i++)
{
    $result .= fgets($file);
}
fclose($file);
file_put_contents('/path/to/file.txt', $result);
相关问题