我在这个网站上搜索了一个答案,但是找不到任何答案.
我有一个表单,我想把输入的内容写入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 $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 ?>
您的表单应如下所示:
原文链接:https://www.f2er.com/php/132048.html<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打开,写入和关闭文件.不要乱了
进一步阅读:
file_put_contents