通过PHP将标头添加到CSV文件

时间:2018-04-14 11:16:55

标签: php html forms csv

我有以下PHP脚本用于创建CSV并将数据从HTML表单收集到CSV文件,但我无法将标题添加到CSV文件的第一行。我是PHP世界的新手,所以如果有人可以使用这段代码来帮助我,我将不胜感激:

<?php

$fieldA = $_POST["prezime"];
$fieldB = $_POST["ime"];
$fieldC = $_POST["datumrodjenja"];
$fieldD = $_POST["mestorodjenja"];
$fieldE = $_POST["rod"];
$fieldF = $_POST["prebivaliste"];
$fieldG = $_POST["brojpasosa"];
$fieldH = $_POST["izdatod"];
$fieldI = $_POST["vazido"];
$fieldJ = $_POST["profesija"];
$fieldK = $_POST["zanimanje"];
$fieldL = $_POST["fiksni"];
$fieldM = $_POST["mobilni"];
$fieldN = $_POST["email"];
$fieldO = $_POST["napomena"];

$keys = array($fieldA,$fieldB,$fieldC,$fieldD,$fieldE,$fieldF,$fieldG,$fieldH,$fieldI,$fieldJ,$fieldK,$fieldL,$fieldM,$fieldN,$fieldO); //THIS IS WHERE YOU PUT THE FORM ELEMENTS ex: array('$fieldA','$fieldB',etc)

$fname = 'prijave.csv';
$fp = fopen($fname,'a');
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

fputcsv($fp, $keys);
fclose($fp);

?>

2 个答案:

答案 0 :(得分:2)

您可以使用键创建一个数组,并创建一个循环来获取值。然后使用fputcsv()编写标题和值:

$keys = ["prezime", "ime", "datumrodjenja", "mestorodjenja", "rod", "prebivaliste",
         "brojpasosa", "izdatod", "vazido", "profesija", "zanimanje", "fiksni", "mobilni",
         "email", "napomena"];

$values = [];
foreach ($keys as $key)
    $values[] = $_POST[$key];

$fname = 'prijave.csv';
$fp = fopen($fname,'a');
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
fputcsv($fp, $keys);
fputcsv($fp, $values);
fclose($fp);

修改:要每次都添加值而不是BOM和标题,您可以检查是否file exists,并仅在文件是新文件时添加它们:

// same code as above ($header + $values)
// then,
$fname = 'prijave.csv';
if (!file_exists($fname)) {
    $fp = fopen($fname,'a');
    //add BOM to fix UTF-8 in Excel
    fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
    fputcsv($fp, $keys);
}
else {
    $fp = fopen($fname,'a');
}
fputcsv($fp, $values);
fclose($fp);

答案 1 :(得分:0)

请查看https://secure.php.net/manual/de/function.fputcsv.php,了解fputcsv的实际工作原理。

该函数的每次调用都会将一行CSV从一个数组写入指定的文件。

第一个例子说明了这一点:

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

因此,在编写最新的数据行之前,您应该使用fputcsv来编写标题。在你的情况下,看起来像这样:

$headers = array("prezime","ime","datumrodjenja","mestorodjenja","rod","prebivaliste","brojpasosa","izdatod","vazido","profesija","zanimanje","fiksni","mobilni","email","napomena");

$fname = 'prijave.csv';
$fp = fopen($fname,'a');
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

fputcsv($fp, $headers);
fputcsv($fp, $keys);
fclose($fp);

我希望,这有帮助。