【问题标题】:How do I make this php script add a line to data.txt or make it write to a different如何让这个 php 脚本在 data.txt 中添加一行或让它写入不同的
【发布时间】:2019-10-30 01:57:43
【问题描述】:

我有一个用于用户输入的 php 脚本,现在我希望这个脚本“添加到现有文件 data.txt(首选)”或为每个名为 $field1 的答案创建一个单独的文件

<?php
$txt = "data.txt";
$fh = fopen($txt, 'w+');
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
 $txt=$_POST['field1'].' - '.$_POST['field2'];
 file_put_contents('data.txt',$txt."\n",FILE_APPEND); //log to data.txt
 exit();
}
 fwrite($fh,$txt); // write information to the file
 fclose($fh); // close the file

?>

这是网站上必须写的表格

"Name - Vote"
"Name - Vote"
"Name - Vote"

现在它会覆盖文件而不是添加到文件中

【问题讨论】:

  • 你能发布你正在做的事情吗?在这里瞎开车?
  • 这是网站上的一个表格,必须写“姓名 - 投票” “姓名 - 投票” “姓名 - 投票” 现在它会覆盖文件而不是添加到文件中
  • 您的代码存在逻辑错误

标签: php variables save user-input save-as


【解决方案1】:

@Eric:读取代码中插入的cmets进行解析

<?php
$txt = "data.txt";
$fh = fopen($txt, 'a'); // the correct open flag for append end of file
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
 $txt=$_POST['field1'].' - '.$_POST['field2'];
 fwrite($fh, $txt . "\n"); // carriage return added (*assumption needed)
 // exit(); // omit
}
 // fwrite($fh,$txt); // write information to the file // pointless, redundant
 fclose($fh); // close the file

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-06
    • 2015-05-15
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多