PHP:除了电子邮件之外还将表单数据写入文本文件?

时间:2016-11-13 15:14:36

标签: php forms

我使用以下代码通过电子邮件发送表单提交的结果。由于我在没有数据库的情况下运行,我喜欢某种其他记录。

<?php
    $to = "me@me.com"; 
    $from = $_REQUEST['email']; 
    $name = $_REQUEST['name']; 
    $headers = "From: $from"; 
    $subject = "New Message"; 
    $fields = array(); 
    $fields{"first_name"} = "first_name";
    $fields{"last_name"} = "last_name"; 
    $fields{"email"} = "email"; 
    $fields{"phone"} = "phone"; 
    $fields{"hospital"} = "hospital"; 
    $fields{"title"} = "title"; 
    $body = "Here is what was sent:\n\n"; 
    foreach($fields as $a => $b){   
        $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); 
    }
    $send = mail($to, $subject, $body, $headers);
?>

除电子邮件外,如何将结果保存到文本文件?我已经看过如何做文字的例子,但除了电子邮件之外没有。

2 个答案:

答案 0 :(得分:0)

你应该检查文件功能:

您可以做的一个例子:

$filePath = 'records.txt';
file_put_contents($filePath, "\nYour text here...", FILE_APPEND);

答案 1 :(得分:0)

应该是这样的:

//Email code here...

if(!$file = fopen('records.txt', 'a+')) {
    echo 'Could not write to file.';
    exit;
}

$content = "Email sent on: " . time() . PHP_EOL . "***" . PHP_EOL . $body . PHP_EOL . "***" . PHP_EOL;

if(fwrite($file, $content) === false) {
    echo 'Could not write to file.';
    exit;
}

fclose($file);

有关详情,请参阅:http://php.net/fwrite