2017年11月9日09:25:56
根据项目实践总结的一个类文件, mac/win下没乱码
简体中文 默认从gb2312转到utf-8
用法:
1 // 导入:2 $arr = CSV::import($filepath);3 4 // 导出:5 $data = ['filename' => 'xxx', 'list' => [[xx,xx,x], [xx,xx,x]]];6 CSV::export($data);
1 'xxx', 'list' => [[xx,xx,x], [xx,xx,x], ....]]40 * @return bool41 */42 public static function export($data)43 {44 if (empty($data['filename']) || empty($data['list'])) {45 self::_SetError('缺少参数filename/list');46 return FALSE;47 }48 $filename = $data['filename']; //文件名49 50 header("Expires: 0");51 header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");52 // 强制下载53 header("Content-Type: application/force-download");54 header("Content-Type: application/octet-stream");55 header("Content-Type: application/download");56 // disposition / encoding on response body57 header("Content-Disposition: attachment;filename={ $filename}");58 header("Content-Transfer-Encoding: binary");59 60 //设置utf-8 + bom ,处理汉字显示的乱码61 echo(chr(0xEF).chr(0xBB).chr(0xBF));62 63 //打开输出缓存64 ob_start();65 66 //打开输出流67 $df = fopen("php://output", 'w');68 69 //数据写入缓存70 foreach ($data['list'] as $row) {71 foreach ($row as $k => $v) {72 is_numeric($v) && ($row[$k] .= "\t"); //防止变为科学计数法显示73 }74 fputcsv($df, $row);75 }76 77 fclose($df);78 echo ob_get_clean();79 exit;80 }81 }