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

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

4
你也应该自己进行一些研究。这个网站是为其他资源提供补充,而不是替代整个互联网。人们很乐意帮助你,但你也需要采取一些措施来帮助自己。 - DMin
5个回答

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);

你需要知道第20个\n的字节数吗? - Patrick
我对fopen()不够熟悉,不知道它是否也将整个文件放入内存中,但如果fopen()使用的内存较少,您可以与fgets()一起使用前20行。 - Patrick

5
为了实现内存高效的解决方案,您可以使用:
$file = new SplFileObject('/path/to/file.txt', 'a+');
$file->seek(19); // zero-based, hence 19 is line 20
$file->ftruncate($file->ftell());

0

抱歉,我误读了问题...

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

1
我认为这将给你一个除了前20行之外的所有文件。如果我理解正确,@Ahsan只想要前20行。 - Surreal Dreams
这看起来更好,但最好将 $i < 20,否则你会读取 21 行 :) 不过你的想法是正确的。 - Surreal Dreams

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);

1
你可以使用file()函数将内容读入数组中,这样就不必手动使用explode()函数来处理数据了。 - Surreal Dreams

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接