I need to save data array to CSV file. The problem is the following: When I open CSV file, I see that 0 row of an array is saved at the same row as a header. Also the last column of a header contains 0, i.e. ‘www0’. How to avoid this?
header("Content-type: text/csv");
header("Pragma: no-cache");
saveCSV($solutionCSV);
function saveCSV($data) {
$outstream = fopen("schedule.csv", "a");
$headers = 'xxx, yyy, zzz, www';
fwrite($outstream,$headers);
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals);
}
array_walk($data, "__outputCSV", $outstream);
fclose($outstream);
}
You need a newline after the headers. Note the change from single- to double-quotes to enable escaping.
If this trips up Windows, use
\r\n:Alternatively, you can rely on
fputcsvto write the headers, too. This is probably the safest method as it will result in a consistent format.