A function to auto create and download in browser a csv while forcing to enclose all or only specified columns
It uses a string, that is quite unlikely to existing in the dataset, which contains at least one space and this forces the the enclosure.
After fputsv does it's job you retrieve the file and replace the forcing string with empty character.
This cannot work in large streams of data unless you modify it but for most applications it's should be sufficient
Just input the columns you want to force enlcose or ['*'] to enclose everything and in case for some strange reason the forcing string is already included in your data you can pass a different non existing string to force enclose
function csvDownload(
array $array,
string $filename = "export.csv",
?string $separator = ",",
?string $enclosure = '"',
?string $escape = "\\",
?array $forceEnclose = [],
string $forceString = '{ || force enclosing || }'
): void
{
$tempFile = fopen('php://memory', 'w');
foreach ($array as $line) {
fputcsv(
$tempFile,
array_map(
function ($value, $key) use ($forceEnclose, $forceString) {
if (
in_array($key, $forceEnclose, true) ||
in_array('*', $forceEnclose, true)
) {
$value .= $forceString;
}
return $value;
},
$line,
array_keys($line)
),
$separator,
$enclosure,
$escape
);
}
rewind($tempFile);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
echo str_replace(
$forceString,
'',
stream_get_contents($tempFile)
);
exit;
}
Magento/Varien_Io_File::streamWriteCsv()
(which ultimately just usesfputcsv
), did you ever find a good solution for this? Possibly usingVarien_File_Csv
? – Goldstein