如何保存多个数据字符串而不删除旧的(在同一文件)


How to save multiple data strings without removing the old ones (in same file)?

如何保存多个数据字符串而不删除旧的(在同一文件)?

我使用POST将数据从表单添加到TXT文件,但它一直覆盖旧数据:

$txt = "joined_teams.txt"; 
$fh = fopen($txt, 'w+'); 
if (isset($_POST['teamname']) && isset($_POST['shortname']) && isset($_POST['1steamid']) && isset($_POST['2steamid']) && isset($_POST['3steamid']) && isset($_POST['4steamid']) && isset($_POST['5steamid'])){ // check if both fields are set
   $txt=$_POST['teamname'].' - '.$_POST['shortname'].' - '.$_POST['1steamid'].' - '.$_POST['2steamid'].' - '.$_POST['3steamid'].' - '.$_POST['4steamid'].' - '.$_POST['5steamid']; 
   file_put_contents('joined_teams.txt',$txt."'n",FILE_APPEND); // log to joined_teams.txt 
   exit(header('location:http://coprogames.com'));
}
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file

你在做同样的事情两次。您只需要调用file_put_contents,并且可以删除fopen/fwrite调用。你只需要:

if (isset($_POST['teamname']) && isset($_POST['shortname']) && isset($_POST['1steamid']) && isset($_POST['2steamid']) && isset($_POST['3steamid']) && isset($_POST['4steamid']) && isset($_POST['5steamid'])){ // check if both fields are set
   $txt=$_POST['teamname'].' - '.$_POST['shortname'].' - '.$_POST['1steamid'].' - '.$_POST['2steamid'].' - '.$_POST['3steamid'].' - '.$_POST['4steamid'].' - '.$_POST['5steamid']; 
   file_put_contents('joined_teams.txt',$txt."'n",FILE_APPEND); // log to joined_teams.txt 
   exit(header('location:http://coprogames.com'));
}

您也可以尝试这样做。

file_put_contents('joined_teams.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);