2010-01-02 96 views
0

我使用以下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 +'。它們需要以逗號分隔值存儲。

任何人都可以建議我如何同時做到這一點?

+1

如果您只需要查看最近一次更改的時間,則可能不需要第二個文件 - 當您追加到第一個文件時,該文件的修改時間將被更新。你可以用mtime()來訪問它。 – 2010-01-02 14:33:52

回答

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); 
} 
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); 
} 
+0

用於'file_put_contents()'的+1 – 2010-01-02 14:42:35