使用php导出csv文件主要是有两个部分的内容:
- 按csv文件的格式准备好数据;
- php header() 函数,它是用来向客户端发送 HTTP 报头的。
下面以一个具体的例子说明:
public function exportCsv()
{
$title = 'ID, 学号, 姓名, 性别' . "\n";
// 这里需要注意,"\n"必须使用双引号
$data = '';
$students = Student::find()->asArray()->all();
// 这里使用的是Yii2.0框架
foreach ($student as $value) {
$id = iconv('utf-8','gb2312',$value['id']);
$number = iconv('utf-8','gb2312',$value['number']);
// 转化字符的编码,下同
$name = iconv('utf-8','gb2312',$value['name']);
$gender = iconv('utf-8','gb2312',$value['gender']);
$data .= $id . ',' .$number . ',' . $name . ',' . $gender;
$data .= "\n";
}
$data = $title.$data; // 到此数据已经准备好
$filename = date('Ymd', time()). '.csv';
$this->setCsvHeader($filename, $data);
}
public function setCsvHeader($filename, $data)
{
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 $data;
}