The following logic should help you on your way:
<?php
$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]);
$j++;
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);
}
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">
<table>
<tbody>
<tr>
<th></th>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr>
<th>A</th>
<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>
</tr>
<tr>
<th>B</th>
<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>
</tr>
<tr>
<th>C</th>
<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>
</tr>
</tbody>
</table>
<input type="submit" name="submit" value="Submit" />
</form>
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…
<?php
$A1 = '';
$A2 = '';
$A3 = '';
$B1 = '';
$B2 = '';
$B3 = '';
$C1 = '';
$C2 = '';
$C3 = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
$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…
A1,A2,A3
B1,B2,B3
C1,C2,C3
How can I accomplish this?