$ composer require symfony/http-foundation
Drupal自带这个包并不需要安装
include_once "./vendor/autoload.php";
$header = [
'Content-Encoding' => 'UTF-8',
'Content-Type' => 'text/csv;charset=UTF-8',
'Content-Disposition' => "attachment;filename=\"mycsv.csv\"",
];
$response = new \Symfony\Component\HttpFoundation\StreamedResponse(function() {
$handle = fopen('php://output', 'w');
// 这里查询你的数据库和设置csv记录.
while (true) {
fputcsv($handle, ['a', 'b', 'c']);
}
fclose($handle);
}, 200, $header);
$response->send();
exit();
方法2原生的PHP
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv;charset=UTF-8');
header('Content-Disposition: attachment;filename="mycsv.csv"');
$handle = fopen('php://output', 'w');
// 这里查询你的数据库和设置csv记录.
while (true) {
fputcsv($handle, ['a', 'b', 'c']);
}
fclose($handle);