前端之家收集整理的这篇文章主要介绍了
PHP从输入写入文件到txt,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
403_0@
我在这个网站上
搜索了一个答案,但是找不到任何答案.
我有一个表单,我想把输入的内容写入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打开,写入和关闭文件.不要乱了
进一步阅读:
file_put_contents