PHP导入导出csv文件 Summer-CSV
2017年11月9日09:25:56
根据项目实践总结的一个类文件, mac/win下没乱码
简体中文 默认从gb2312转到utf-8
https://gitee.com/myDcool/PHP-CSV
用法:
1 // 导入: 2 $arr = CSV::import($filepath); 3 4 // 导出: 5 $data = ['filename' => 'xxx', 'list' => [[xx,xx,x], [xx,xx,x]]]; 6 CSV::export($data);
1 <?php 2 3 class CSV 4 { 5 public static $csvError = ''; 6 7 public static function _SetError($error) 8 { 9 self::$csvError = $error; 10 } 11 12 /** 13 * 读取csv文件成数组 14 * @param string $filePath 文件路径 15 * @return array|bool 16 */ 17 public static function import($filePath) 18 { 19 setlocale(LC_ALL, 'zh_CN'); 20 21 if(!file_exists($filePath) || !is_readable($filePath)) { 22 self::_SetError('文件不存在或者不可读'); 23 return FALSE; 24 } 25 26 $rows = array(); 27 $fp = fopen($filePath, 'rb'); 28 while (!feof($fp)) { 29 30 $row = str_replace(array("\r\n", "\r", "\n"), '', fgets($fp)); 31 $rows[] = explode(',', iconv('GB2312', 'UTF-8', $row)); //简体中文编码转为 utf-8, gbk 兼容gb2312 32 33 } 34 return $rows; 35 } 36 37 /** 38 * 输出 UTF-8 编码的csv文件 39 * @param array $data ['filename' => 'xxx', 'list' => [[xx,xx,x], [xx,xx,x], ....]] 40 * @return bool 41 */ 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 body 57 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 }