删除文件追加后的第一行


Delete first lines after file append

我使用附加代码在.txt文件中写入新行:

$fh = fopen('ids.txt', 'a');
fwrite($fh, "Some ID'n");
fclose($fh);

我希望这个文件只有20行,并删除第一行(旧的)。

读取中的所有行,在底部添加行,然后只使用最后20行重写文件。

我不擅长php,但如果你只想要20行,你肯定会做这样的伪代码。

lines <- number of lines you want to write
if lines > 20
  yourfile <- new file
  yourfile.append (last 20 lines of your text)
else if lines = 20
  your file <- new file
  yourfile.append (your text)
else
  remainingtext <- the last [20-lines] of yourfile
  yourfile.append (remaining text + your text)

编辑:一种更简单的方法,但可能效率较低[我认为这相当于NovaDenizen的解决方案]

yourfile <- your file
yourfile.append(yourtext)
newfilearray <- yourfile.tokenize(newline)(http://php.net/manual/en/function.explode.php)
yourfile <- newfile
for loop from i=newfilearray.size-21 < newfilearray.size
  yourfile.append (newfilearray[i])
$content=file($filename);
$content[]='new line of content';
$content[]='another new line of content';
$file_content=array_slice($content,-20,20);
$file_content=implode("'n",$file_content);
file_put_contents($filename,$file_content);

您可以使用file()函数将文件加载为数组。然后将新内容添加到加载的数组中,将其切片为20个元素,从该数组中生成"输入"文本并将其保存到文件中。

您可以使用函数file:

http://php.net/manual/en/function.file.php

将整个文件读取到数组中。

也就是说,你需要做以下事情:

1.)将现有文件读取到阵列中:

$myArray= file("PathToMyFile.txt");

2.)反转数组,使最旧的条目位于最上面:

$myArray= array_reverse($myArray);

3.)将你的新条目添加到该数组的末尾。

$myArray[] = $newEntry + "'n";

4.)再次反转:

$myArray= array_reverse($myArray);

5.)把前20行写回你的文件(这是你的"新"+19行旧行):

$i = 1; 
$handle = fopen("PathToMyFile.txt", "w"); //w = create or start from bit 0
foreach ($myArray AS $line){
   fwrite($handle, $line); //line end is NOT removed by file();
   if ($i++ == 20){
     break;
   }
}
fclose($handle);

为什么不直接使用file_put_contents("yourfile.txt",");将文件内容设置为无内容,然后只设置file_put_contents("yourfile.txt",$newContent)?

你是想做别的事情,还是我错过了什么?