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

This should work as well without huge memory usage

$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 に答える