PHP生成CSV文件及其导出CSV

PHP生成CSV文件

//提前创建对应的文件路径
$filePath = '/tmp/乐杨俊/';
if (!file_exists($filePath)) {
   mkdir($filePath, 0777, true); 
}

//创建CSV文件
$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导出方法

//调用demo
$filename = '乐杨俊-'.date('Ymd');
$this->exportData($filename,"id,日期,金额,交易单ID",[
	[1,'2020-07-28',1000,123456789],
	[2,'2020-07-29',1000,222334456],
]);

/**
 * 导出CSV
 * @param $filename 文件名
 * @param $title 标题
 * @param $data 数据
 */
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');
}

你可能感兴趣的:(PHP)