同时将一个值写入两个文本文件
问题描述:
我使用以下php将HTML <form>
的内容发送到文本文件:同时将一个值写入两个文本文件
$filename = "polls"."/".time() .'.txt';
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
if ($handle) {
fwrite($handle, $_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
在创建文本文件的同时,使用表单的内容,我也想写时间()到已经存在的文件,所以将使用'a +'。它们需要以逗号分隔值存储。
任何人都可以建议我如何同时做到这一点?
答
只需打开两个文件:
$handle1 = fopen($filename1, "w+");
$handle2 = fopen($filename2, "a+");
if ($handle1 && $handle2) {
fwrite($handle1, $_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fwrite($handle2, time() + "\n");
}
if ($handle1) {
fclose($handle1);
}
if ($handle2) {
fclose($handle2);
}
答
你也可以写使用file_put_contents()文件(包括追加)。
if (isset($_POST["submitwrite"])) {
// Could perhaps also use $_SERVER['REQUEST_TIME'] here
$time = time();
// Save data to new file
$line = sprintf("%s¬%s¬%s¬%s¬%s¬%d",
$_POST["username"], $_POST["pollname"], $_POST["ans1"],
$_POST["ans2"], $_POST["ans3"], $time);
file_put_contents("polls/$time.txt", $line);
// Append time to log file
file_put_contents("timelog.txt", "$time,", FILE_APPEND);
}
+0
用于'file_put_contents()'的+1 – 2010-01-02 14:42:35
如果您只需要查看最近一次更改的时间,则可能不需要第二个文件 - 当您追加到第一个文件时,该文件的修改时间将被更新。你可以用mtime()来访问它。 – 2010-01-02 14:33:52