Php 将HTML表格中的多行输入作为单独的行写入CSV文件?

Php 将HTML表格中的多行输入作为单独的行写入CSV文件?,php,html,arrays,forms,csv,Php,Html,Arrays,Forms,Csv,我已经创建了一个HTML表,我想用它来收集值并将它们存储在CSV文件中。HTML代码如下所示: <form method="post"> <table> <tbody> <tr> <th></th> <th>1</th> <th>2</th> <th>3</th> &l

我已经创建了一个HTML表,我想用它来收集值并将它们存储在CSV文件中。HTML代码如下所示:

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

我如何才能做到这一点?

以下逻辑应该可以帮助您实现这一目标:

<?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);
}

这就成功了!非常感谢您的洞察力!很高兴我能帮忙!
A1,A2,A3
B1,B2,B3
C1,C2,C3
<?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);
}