PHP从输入写入文件到txt
发布时间:2020-12-13 16:41:36 所属栏目:PHP教程 来源:网络整理
导读:我在这个网站上搜索了一个答案,但是找不到任何答案. 我有一个表单,我想把输入的内容写入txt文件.为了简单起见,我只是写了一个简单的表单和一个脚本,但它让我一个空白的页面.这是我得到的 htmlhead title/title/headbody form form action="myprocessingscrip
我在这个网站上搜索了一个答案,但是找不到任何答案.
我有一个表单,我想把输入的内容写入txt文件.为了简单起见,我只是写了一个简单的表单和一个脚本,但它让我一个空白的页面.这是我得到的 <html> <head> <title></title> </head> <body> <form> <form action="myprocessingscript.php" method="post"> <input name="field1" type="text" /> <input name="field2" type="text" /> <input type="submit" name="submit" value="Save Data"> </form> <a href='data.txt'>Text file</a> </body> 这里是我的PHP文件 <?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 ?>
您的表单应如下所示:
<form action="myprocessingscript.php" method="POST"> <input name="field1" type="text" /> <input name="field2" type="text" /> <input type="submit" name="submit" value="Save Data"> </form> 和PHP <?php if(isset($_POST['field1']) && isset($_POST['field2'])) { $data = $_POST['field1'] . '-' . $_POST['field2'] . "n"; $ret = file_put_contents('/tmp/mydata.txt',$data,FILE_APPEND | LOCK_EX); if($ret === false) { die('There was an error writing this file'); } else { echo "$ret bytes written to file"; } } else { die('no post data to process'); } 我写了/tmp/mydata.txt,因为这样我现在正好在哪里.使用data.txt写入当前工作目录中的该文件,我在此示例中不知道什么. file_put_contents打开,写入和关闭文件.不要乱了 进一步阅读: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |