public function test()
{
$data = array(
array(
'name' => '对对对',
'score' => 80,
'grade' => '急急急'
),
array(
'name' => '嗯嗯嗯',
'score' => 70,
'grade' => '黑乎乎'
),
array(
'name' => '正在',
'score' => 80,
'grade' => '也一样'
),
array(
'name' => '啊啊啊',
'score' => 203,
'grade' => '日日日'
)
);
$titleList = array('姓名', '总分', '等级');
$fileName = '高三(3)班 7 月份考试结果';
//ini_set("max_execution_time", "3600");
$csvData = '';
// 标题
$nums = count($titleList);
for ($i = 0; $i < $nums - 1; $i++) {
$csvData .= '"' . $titleList[$i] . '",';
}
$csvData .= '"' . $titleList[$nums - 1] . ""
";
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 . ""
";
}
$i++;
}
unset($data[$key]);
}
$csvData = mb_convert_encoding($csvData, "cp936", "UTF-8"); (这句解决Excel版本低导出乱码问题)
$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();
}