PHP生成CSV文件
$filePath = '/tmp/乐杨俊/';
if (!file_exists($filePath)) {
mkdir($filePath, 0777, true);
}
$fileName = $filePath . iconv('UTF-8', 'GB2312//IGNORE', "leyangjun.csv";
$fp= fopen($fileName, 'w');
chmod($fileName, 0777);
fputcsv($fp, explode(',', mb_convert_encoding('姓名,年龄', 'gbk', 'utf-8')));
fputcsv($fp,[iconv('UTF-8', 'GB2312//IGNORE', '乐杨俊'),18]);
fputcsv($fp,[iconv('UTF-8', 'GB2312//IGNORE', '乐杨俊2'),18]);
fputcsv($fp,[iconv('UTF-8', 'GB2312//IGNORE', '乐杨俊3'),18]);
fclose($fp);
CSV导出方法
$filename = '乐杨俊-'.date('Ymd');
$this->exportData($filename,"id,日期,金额,交易单ID",[
[1,'2020-07-28',1000,123456789],
[2,'2020-07-29',1000,222334456],
]);
protected function exportData($filename,$title,$data){
header("Content-Type: text/csv;charset=UTF-8");
header("Content-Type: application/force-download;");
header('Content-Disposition: attachment; filename="' . $filename.".csv");
if(is_array($title)){
$outputData = implode(",", $title)."\n";
}else{
$outputData = $title."\n";
}
if(!empty($data) && is_array($data)){
foreach($data as $k){
$outputData .= implode(",",$k)."\n";
}
}
$outputData = urldecode($outputData);
echo mb_convert_encoding($outputData,'gbk','utf-8');
}