如何删除.txt文件中的行?但是保留第一个十行?
这是我到目前为止的代码:
<?php
$hiScore = $_POST['hiScore'] ? $_POST['hiScore'] : 'not set';
$theInput = $_POST['theInput'] ? $_POST['theInput'] : 'not set';
$file = fopen('LeaderBoard.txt','a+');
fwrite($file, ' '.$hiScore.' - Score Name: '.$theInput.' '.PHP_EOL);
fclose($file);
$lines = file("LeaderBoard.txt");
natsort($lines);
$lines=array_reverse($lines);
file_put_contents("LeaderBoardScores.txt", implode("'n 'n 'n 'n 'n 'n 'n 'n", $lines));
$handle = fopen("LeaderBoardScores.txt");
$output = '';
$i = 0;
while (($line = fgets($handle)) !== false) {
$output .= $line . "'n";
if ($i++ >= 10)
break;
}
fclose($handle);
file_put_contents($output, "Leader.txt");
?>
我不确定如果 staps 在 PHP 中工作,但也许检查文件,如果行 = 10 以上不会向文件发布任何内容?
用户看到的记分板:排行榜分数.txt应只看到前 10 名
排行榜.txt是发布数据的地方,然后进行排序,以便人们在排行榜分数中查看.txt
您可以使用
fgets()
遍历每一行,并在第 10 行之后中断:
<?php
$handle = fopen($path_to_file);
$output = '';
$i = 0;
while (($line = fgets($handle)) !== false) {
$output .= $line . "'n";
if ($i++ >= 10)
break;
}
fclose($handle);
file_put_contents($output, $path_to_file);
http://php.net/manual/en/function.fgets.php
在这种情况下,while (($line = fgets($handle)) !== false)
一次循环遍历现有文件中的行。 $output
收集行的内容。 $i
计算到目前为止我们添加到$output
的行数,以便我们可以在正确的时间停止(break
)。