将脱机html表单数据存储在csv文件中


store offline html form data in a csv file

我正在寻找一个简单的解决方案,希望这是一个简单问题。我想让一台笔记本电脑设置一个离线html文件,这个文件的格式很短,可以提供csv文件。我一直在关注fputcsv()函数来实现这一点,但我不是最有天赋的程序员。如果我有一个看起来像这样的简单表单:

<?php
    if(isset($_POST['submit']))
    {
        $myfile = fopen('file.csv', 'w');
        fputcsv($myfile,
            array($_POST['first-name'], $_POST['last-name'], $_POST['email']));
        fclose($myfile);
    }
?>
<article role="main">
    <header role="banner">
        <h1>Email Updates</h1> 
    </header> 
    <section>
    <form id="form1" name="form1" method="post" action="<?=$_SERVER['PHP_SELF'];?>">
        <input type="text" id="first-name" maxlength="100" autocorrect placeholder="First name" />
        <input type="text" id="last-name" maxlength="100" autocorrect placeholder="Last name" />
        <input type="text" id="email" maxlength="100" autocorrect placeholder="Email address" />
        <button type="submit" id="submit" class="oneup">Submit</button>
    </form>
    </section> 
</article>

我需要什么样的代码才能让它提供一个简单的csv文件?

当(如果)表单提交(正确)时,执行以下操作:

if( $fp = fopen('file.csv', 'w') )
{
  fputcsv($fp, $_POST);
}
fclose($fp);

提交此表单时,它将填充$_POST数组。

因此,您应该添加一些PHP代码来处理提交的值。

例如:

<?php
    if(isset($_POST['submit']))
    {
        $myfile = fopen('file.csv', 'w');
        fputcsv($myfile,
            array($_POST['first-name'], $_POST['last-name'], $_POST['email']));
        fclose($myfile);
    }
?>

类似于djot的答案,我会使用这个:

if( $fp = fopen('file.csv', 'w') ){
    fputcsv($fp, print_r($_POST, true));
}
fclose($fp);

请注意带有true标志的print_r,因为这使它更易于阅读。

如果你真的想把它写成CSV,只需使用:

$data = implode(',' $_POST);
if( $fp = fopen('file.csv', 'w') ){
    fputcsv($fp, $data);
}
fclose($fp);