Search code examples
phphtmlexport-to-csv

Exporting a HTML form to a CSV file


I have borrowed some code from an older post to try and achieve this, but it is not working as expected. There are two issues. First the html:

<!DOCTYPE html>
<html>
    <title>Test Form</title>
<head>
</head>
<body>
<form name="xyz_form" action="proces.php" method="post">
    <section class="border-bottom">
        <div class="content">
            <h3>ID Number</h3>
            <div class="form-control-group">
                <div class="form-control form-control-number">
                    <input type="number" name="id_number" id="id_number">
                </div>
            </div>
                    <h3>First Name</h3>
            <div class="form-control-group">
                <div class="form-control form-control-text">
                    <input type="text" name="first_name" id="first_name">
                </div>
            </div>
        </div><!--.content-->
    <section class="data-capture-buttons one-buttons">
       <div class="content">
          <input type="submit" value="Submit">
       </div>
    </section><!--.data-capture-buttons-->
</form> 
</body>
</html>

and the PHP code:

<?php
$fieldA = $_POST['id_number'];
$fieldB = $_POST['first_name'];

$keys = array($fieldA,$fieldB);
$csv_line = $keys;
foreach( $keys as $key ){
    array_push($csv_line,'' . $_GET[$key]);
}
$fname = 'file_to_write_to.csv';
$csv_line = implode(',',$csv_line);
if(!file_exists($fname)){$csv_line = '\r\n' . $csv_line;}
$fcon = fopen($fname,'a');
$fcontent = $csv_line;
fwrite($fcon,$csv_line);
fclose($fcon);
?>

The form runs and does write to the CSV file, but at runtime it throws two warnings:

Warning: Undefined array key 3 in E:\XAMPP\App\xampp\htdocs\test_form\proces.php on line 8

Warning: Undefined array key "Third" in E:\XAMPP\App\xampp\htdocs\test_form\proces.php on line 8

(3 and "Third" are the two values intered in the form.)

Now it writes to the CSV but the format is incorrect.

1,First,,2,Second,,3,Third,,

It is adding an extra comma after the two values and not recognising the \r\n for the new lines.

I have tried things ike changing the quotes from single to double. I have also tested changing line 6 $csv_line = $keys; to $csv_line = array(); as suggested in the original post, but that does not fix the problem.

Can some kind person help me sort this out? Thanks.


Solution

  • @ADyson clue was the hint to use fputcsv. I need the extra parameter eol: to change the default end of line from \n to \r\n

    Here's my PHP now.

    <?php
    $fieldA = $_POST["id_number"];
    $fieldB = $_POST["first_name"];
    
    $keys = array($fieldA, $fieldB);
    $file_pointer = fopen("file_to_write_to.csv","a");
    fputcsv($file_pointer, $keys, eol: "\r\n");
    fclose($file_pointer);
    ?>