PHP - 向文本文件添加行会覆盖旧的 lines.Also 奇怪的 s:文本文件中的字符?

PHP - Adding line to textfile overwrites old lines.Also weird s: characters in textfile?

向文本文件添加一行的最佳方法是什么?当我 运行 下面的代码时,它会覆盖所有行。

此外,添加一行时它包含一些 "s:4:" & s:60: 个字符。这是什么意思?我只想将 $photourl 添加到 urls.txt

<?php
  foreach ($_POST['photoselect'] as $photourl) {
   file_put_contents($target_dir . '/urls.txt', $photourl);
   $fp = fopen($target_dir . '/urls.txt','w'); 
   fwrite($fp,serialize($photourl));
  }
?>

打开文件时,最后一个参数表示您希望如何设置文件指针。使用 'w',这会截断文件,您可能想要 'a',这意味着将指针放在文件的末尾。 (参见 http://php.net/manual/en/function.fopen.php 模式)

除非你的内容包含特殊字符,否则只写它而不是serialize它。

您的代码每次都会覆盖文件...

$fp = fopen($target_dir . '/urls.txt','a'); 
foreach ($_POST['photoselect'] as $photourl) {
     fwrite($fp,$photourl.PHP_EOL);
}
fclose($fp);

您可以附加 file_put_contents
file_put_contents($target_dir . '/urls.txt', $photourl, FILE_APPEND);