这是对我有用的解决方案。我正在使用 Symfony 4.4。
headers
=> 包含您的标题。
lines
=> 包含你的台词。
$response = new StreamedResponse();
$response->headers->set('Content-Type', 'application/force-download');
$response->headers->set('Content-Disposition', $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'export.csv'
));
$response->setCallback(function () use ($headers, $lines) {
$handle = fopen('php://output', 'w+');
// Mandatory: Use bom + "Content-Type: application/force-download" => to allow to display special characters with excel
fwrite($handle, $bom = chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF')));
// headers
fputcsv($handle, $headers, ';');
// data
foreach ($lines as $line) {
fputcsv($handle, $line, ';');
}
fclose($handle);
});