3

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

4

5 回答 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);
于 2010-12-10T15:04:02.877 回答
5

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

$file = new SplFileObject('/path/to/file.txt', 'a+');
$file->seek(19); // zero-based, hence 19 is line 20
$file->ftruncate($file->ftell());
于 2010-12-10T15:24:40.270 回答
0

抱歉,误读了问题...

$filename = "blah.txt";
$lines = file($filename);
$data = "";
for ($i = 0; $i < 20; $i++) {
    $data .= $lines[$i] . PHP_EOL;
}
file_put_contents($filename, $data);
于 2010-12-10T15:03:19.410 回答
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);
于 2010-12-10T15:05:39.153 回答
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);
于 2014-09-04T06:48:04.473 回答