PHP导出数据到CSV文件函数 csv_export()
后台往往需要导出各种数据到 Excel文档中。通常我们是导出 .csv文件格式,PHP导出函数参考代码如下:
/** * 导出数据到CSV文件 * * @param array $data 二维数组(模拟数据表记录) * @param array $titleList 标题数组列表 * @param string $fileName CSV文件名 */ function csv_export(&$data, $titleList = array(), $fileName = '') { ini_set("max_execution_time", "3600"); $csvData = ''; // 标题 $nums = count($titleList); for ($i = 0; $i < $nums - 1; $i++) { $csvData .= '"' . $titleList[$i] . '",'; } $csvData .= '"' . $titleList[$nums - 1] . "\"\r\n"; foreach ($data as $key => $row) { $i = 0; foreach ($row as $_key => $_val) { $_val = str_replace("\"", "\"\"", $_val); if ($i < ($nums - 1)) { $csvData .= '"' . $_val . '",'; } elseif ($i == ($nums - 1)) { $csvData .= '"' . $_val . "\"\r\n"; } $i++; } unset($data[$key]); } $csvData = mb_convert_encoding($csvData, "cp936", "UTF-8"); $fileName = empty($fileName) ? date('Y-m-d-H-i-s', time()) : $fileName; $fileName = $fileName . '.csv'; header("Content-type:text/csv;"); header("Content-Disposition:attachment;filename=" . $fileName); header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); header('Expires:0'); header('Pragma:public'); echo $csvData; die(); }
示例:
$data = array( array( 'name' => 'jake', 'score' => 80, 'grade' => 'A' ), array( 'name' => 'jin', 'score' => 70, 'grade' => 'A' ), array( 'name' => 'john', 'score' => 80, 'grade' => 'A' ), array( 'name' => 'ben3', 'score' => 203, 'grade' => 'B3' ) ); $titleList = array('姓名', '总分', '等级'); $fileName = '高三(3)班 7 月份考试结果'; csv_export($data, $titleList, $fileName);