Reputation: 12537
I am trying to convert the below array to a downloadable csv with three columns and three rows. For some reason, the below functions create four columns instead of three with some of the rows shifted over.
I was wondering if someone can help me identify why this is?
Many thanks in advance!
$ary = array(
array("1", "Bob", "Saget"),
array("2", "Luke", "Skywalker"),
array("3", "Owen", "Wilson")
);
$csv = arrayToCsv($ary);
downloadCSV($csv);
function arrayToCsv($array) {
$csv = array();
foreach ($array as $item) {
if (is_array($item)) {
$csv[] = arrayToCsv($item) . "\n";
} else {
$csv[] = $item;
}
}
return implode(',', $csv);
}
function downloadCSV($csv){
$fileName = 'customer-list.csv';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $fileName);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
echo $csv;
exit;
}
Upvotes: 0
Views: 60
Reputation: 780688
Your outer call to arrayToCsv()
calls itself for each element of the array. The inner call puts commas between each element of the sub-array, and then adds a newline to the end. The outer call collects these in a new array, and then separates them with commas. This puts an extra comma at the beginning of each line except the first.
You need to process the outer array differently from the sub-arrays. Implode with ,
when processing the sub-arrays, implode with \n
when processing the outer array.
function arrayToCsv($array) {
return implode("\n", array_map(function($subarray) {
return implode(",", $subarray);
}, $array));
}
Or you could just use fputcsv
:
$fp = fopen("php://stdout", "w");
foreach ($ary as $row) {
fputcsv($fp, $row);
}
fclose($fp);
Upvotes: 2