同时将一个值写入两个文本文件

时间:2010-01-02 14:22:15

标签: php

我使用以下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);
        }

在创建文本文件的同时,使用表单的内容,我还想将time()写入已经存在的文件,因此将使用'a +'。它们需要以逗号分隔值存储。

有人可以建议我如何同时做到这一点吗?

2 个答案:

答案 0 :(得分:5)

只需打开两个文件:

$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);
}

答案 1 :(得分:2)

您还可以使用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);
}