I have the following PHP script for creating CSV and collecting data from HTML form to CSV file, but I can’t add headers to the first row of CSV file. I’m a newbie in PHP world so I’ll appreciate if anyone can use this code to help me with that:
JavaScript
x
<?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);
?>
Advertisement
Answer
You could create a array with your keys, and create a loop to get values. Then use fputcsv()
to write header and values:
JavaScript
$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);
Edit: To add values but not BOM and headers each time, you could check if the file exists, and add them only if the file is new:
JavaScript
// 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);