There are two arrays that I’d like to save as CSV file from PHP. The problem is that this code works only for the first Call. E.g. in the below-given example I can save only array1, but array2 is not saved. If I swap places of array1 and array2, then array2 will be saved instead of array1. What’s actually wrong in my code and how could I solve this problem?
header("Content-type: text/csv");
header("Pragma: no-cache");
$headers = array('xxx','yyy','zzz');
saveCSV($array1,"file1.csv",$headers);
header("Content-type: text/csv");
header("Pragma: no-cache");
$headers = array('aaa','bbb','ccc');
saveCSV($array2,"file2.csv",$headers);
function saveCSV($data,$fileName,$headers) {
$outstream = fopen($fileName, "a");
file_put_contents($fileName, "");
if ($headers != 0)
fputcsv($outstream,$headers);
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals);
}
array_walk($data, "__outputCSV", $outstream);
fclose($outstream);
}
Your setting the headers, twice.
Trying building up your csv data output, then once completed set the headers once.
Also you have a function declaration within another, which i’m sure is invalid.
move __outputCSV somwehere else, or maybe you intended it to be a closure?