使用CVS输入打印变量名称

时间:2016-10-20 15:55:07

标签: php forms csv variables

我将字段输入传递给.csv表,但我想知道是否可以将变量名称与值一起打印?

以下是我打印到.cvs的方式:

PHP

<?php
$csvdata = $firstName . ", " . $lastName . ", " . $homeAddress . ", " . $homeAddressTwo . ", " . $city . ", " . $province . ", " . $postalCode . ", " . $homePhone . ", " . $personalEmail . ", " . $confirmEmail . ", " . $oectaNumber . ", " . $memberStatus . ", " . $teacherTraining . ", " . $teachingYears . "," . $employmentHistoryValues;
$fp = fopen("formdata.csv", "a");
if($fp)
    {
    fwrite($fp, $csvdata . "\n");
    fclose($fp);
    }
?>

这就是我想要它的样子:

Array ( [0] => WLU [1] => Math [2] => 2016 )

以下是我处理viariables的方法:

$educationHistoryValues = "";
foreach(print_r($_POST["educationHistory"]) as $educationValue)
{
    $educationHistoryValues .= $educationValue;
}

输入数据:

<div id="educationHistory" name="educationHistory[]">
<input type="text" class="three-lines" name="educationHistory[]" id="educationInstitution_1" placeholder="Institution" onblur="this.placeholder='Institution'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />

<input type="text" class="three-lines" name="educationHistory[]" id="degreeFromInstitution_1" placeholder="Degree/Diploma" onblur="this.placeholder='Degree/Diploma'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />

<input type="date" class="three-lines" name="educationHistory[]" id="educationalDates_1" />
                            <input type="button" value="+" onclick="addEducation()" />
                        </div><!--end educationHistory Div -->                
                    </div><!--end of education div-->

在CSV文档本身中,结果很容易破译,但我绘制的形式有一堆动态输入,它们将生成多维数组,而一些输入是textareas,所以我想测试这个理论

1 个答案:

答案 0 :(得分:0)

例如,您可以使用列名创建标题csv行。你可以通过以下方式实现这一目标:

  $csv = 'col1, col2.....'.PHP_EOL;
  foreach ($data as $item) {
      $csv .= $item['val1'].','.$item['val2'].....PHP_EOL;
  }
  // write $csv to file

如果您在excel或open office中打开csv文件,这将非常有用。

但是如果你想要键名+值:

  foreach ($data as $key => $item) {
      $csv .= $key.'=>'.$item['val1'].',';
  }

这是一个dimensionl数组的示例。如果你有多维,你将有嵌套循环。