Solution 1 :

The following logic should help you on your way:

$A1 = $A2 = $A3 = $B1 = $B2 = $B3 = $C1 = $C2 = $C3 = '';

function clean_text($string)
    $string = trim($string);
    $string = stripslashes($string);
    $string = htmlspecialchars($string);
    return $string;

// store form data (records: A1-A3, B1-B3 and C1-C3) in array $cleanFormVars 
$i = 0;
$j = 0;
if (isset($_POST["submit"])) {
    $formVars = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"];
    foreach($formVars as $var) {
        $cleanFormVars[$i][] = clean_text($_POST[$var]);
        if($j % 3 === 0) $i++; // create a record(row) for A1-A3, B1-B3, and C1-C3

// write the records(rows) in array $cleanFormVars to .csv
$file_open = fopen("input.csv", "a");
foreach($cleanFormVars as $fields) {
    fputcsv($file_open, $fields);

Problem :

I have created an HTML table that I’d like to use for collecting values and storing them in a CSV file. The HTML code looks something like this:

<form method="post">

        <td><input type="text" class="form-control" name="A1" /></td>
        <td><input type="text" class="form-control" name="A2" /></td>
        <td><input type="text" class="form-control" name="A3" /></td>
        <td><input type="text" class="form-control" name="B1" /></td>
        <td><input type="text" class="form-control" name="B2" /></td>
        <td><input type="text" class="form-control" name="B3" /></td>
        <td><input type="text" class="form-control" name="C1" /></td>
        <td><input type="text" class="form-control" name="C2" /></td>
        <td><input type="text" class="form-control" name="C3" /></td>

<input type="submit" name="submit" value="Submit" />


I plan on having the PHP code in the same web page file, prior to the HTML code being called, to perform the action of taking the input and putting it into a CSV file. Something like this to begin with…


$A1 = '';
$A2 = '';
$A3 = '';
$B1 = '';
$B2 = '';
$B3 = '';
$C1 = '';
$C2 = '';
$C3 = '';

function clean_text($string)
 $string = trim($string);
 $string = stripslashes($string);
 $string = htmlspecialchars($string);
 return $string;


   $A1 = clean_text($_POST["A1"]);
   $A2 = clean_text($_POST["A2"]);
   $A3 = clean_text($_POST["A3"]);
   $B1 = clean_text($_POST["B1"]);
   $B2 = clean_text($_POST["B2"]);
   $B3 = clean_text($_POST["B3"]);
   $C1 = clean_text($_POST["C1"]);
   $C2 = clean_text($_POST["C2"]);
   $C3 = clean_text($_POST["C3"]);      

   $file_open = fopen("input.csv", "a");

…but I’m stuck at this point. I’m guessing that “fputcsv” would be my friend, but I’m not sure how to apply it. This table represent three rows of three columns; my goal is to have three lines added to the CSV file, comma delimited. Something like…


How can I accomplish this?


Comment posted by beetlejuice

This did the trick! Thank you so much for your insight!

Comment posted by jibsteroos

Glad I could help!