0

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

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

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

4

5 回答 5

1

读入所有行,在底部添加您的行,然后仅用最后 20 行重写文件。

于 2013-08-07T21:24:23.087 回答
1

我不擅长 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])
于 2013-08-07T21:27:28.600 回答
0

您可以使用以下功能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);
于 2013-08-07T21:42:46.793 回答
0
$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 个元素,从该数组中“输入”文本并将其保存到文件中。

于 2013-08-07T21:47:43.433 回答
-1

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

您是在尝试做其他事情还是我错过了什么?

于 2013-08-07T21:24:42.887 回答