PHP将文件从输入写入txt [英] PHP write file from input to txt
问题描述
我已经在该站点附近搜索了答案,但是找不到答案.
I've searched around this site for an answer but couldnt find any.
我有一个表格,我想将输入内容写入txt文件.为了简单起见,我只写了一个简单的表单和脚本,但是它一直让我空白.这就是我得到的
I have a form and I'd like to get the contents of the input written into a txt file. To make it simple I just wrote a simple form and a script but it keeps getting me a blank page. Here is what I got
<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
?>
推荐答案
您的表单应如下所示:
Your form should look like this :
<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'] . "\r\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
会在当前工作目录中写入该文件,在您的示例中我一无所知.
I wrote to /tmp/mydata.txt
because this way I know exactly where it is. using data.txt
writes to that file in the current working directory which I know nothing of in your example.
file_put_contents
为您打开,写入和关闭文件.别惹它.
file_put_contents
opens, writes and closes files for you. Don't mess with it.
进一步阅读: file_put_contents
这篇关于PHP将文件从输入写入txt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!