удалите все строки, кроме первых 20, с помощью php


Как удалить все строки, кроме первых 20, с помощью php из текстового файла?

Author: codaddict, 2010-12-10

5 answers

Для эффективного решения с использованием памяти вы можете использовать

$file = new SplFileObject('/path/to/file.txt', 'a+');
$file->seek(19); // zero-based, hence 19 is line 20
$file->ftruncate($file->ftell());
 5
Author: Gordon, 2010-12-15 12:23:29

Если загрузка всего файла в память возможна, вы можете сделать:

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

Лучшим решением было бы использовать функцию усекать который принимает дескриптор файла и новый размер файла в байтах следующим образом:

// 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);
 7
Author: codaddict, 2010-12-10 15:22:26

Прошу прощения, неправильно прочитал вопрос...

$filename = "blah.txt";
$lines = file($filename);
$data = "";
for ($i = 0; $i < 20; $i++) {
    $data .= $lines[$i] . PHP_EOL;
}
file_put_contents($filename, $data);
 0
Author: fire, 2010-12-10 15:08:28

Что-то вроде:

$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);
 0
Author: Ben L., 2010-12-10 15:28:28

Это также должно работать без огромного использования памяти

$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);
 0
Author: Ajjaah, 2014-09-04 06:48:04