我已经这样做了一段时间,并且已经浏览了堆栈上的其他选项,但无法使其工作。(我很菜鸟,对不起!
我有一个表单,我想将数据发送到我的 txt 文件,但它只是没有写入。
非常感谢任何帮助,谢谢!!
我的 HTML 表单:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>php test</title>
</head>
<title></title>
</head>
<body>
<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='/tmp/mydata.txt'>Text file</a>
</body>
还有我的PHP。
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "n";
$ret = fwrite('/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');
}
您需要先打开文件,然后才能使用 fwrite()
写入该文件。
$fp = fopen('/tmp/mydata.txt', 'w');
$ret = fwrite($fp, $data);
//and don't forget to close it
fclose($fp);
if($ret === false) {
...
根据您在问题中使用的标志,我认为您可能想到的功能是file_put_contents
(在此处查看文档(而不是fwrite
。
尝试添加以下代码行:
$myfile = fopen("/tmp/mydata.txt", "w") or die("Unable to open file!");
在 fwrite(( 之前,您现在可以在文件中插入数据/文本:
fwrite($myfile, $data);