Question

I'm looking for a simple solution to what is hopefully a simple problem. I want to have a laptop set up with an offline html file with a very short form that feeds a csv file. I've been eyeing the fputcsv() function to do this, but I'm not the most talented programmer. If I have a simple form that looks like this:

<?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>

what kind of code do I need to have it feed a simple csv file?

Was it helpful?

Solution

When this form is submitted, it will populate the $_POST array.

So, you should add some PHP code that handles the submitted values.

For example:

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

OTHER TIPS

When (if) the form is submitted (correctly), do this:

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

Similar to djot's answer, I'd use this:

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

Note the print_r with the true flag, as this makes it more human readable.

If you actually wanted to write it as a CSV, just use:

$data = implode(',' $_POST);
if( $fp = fopen('file.csv', 'w') ){
    fputcsv($fp, $data);
}
fclose($fp);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top