您的位置:首页 > 编程语言 > PHP开发

PHP(Thinkphp框架)将数据表导出csv文件

2017-08-17 13:27 706 查看
CSV文件类似于excel文件,用逗号表示分隔符,换行符代表该行结束

访问方法

public function export_csv()
{
$csvModel = M('select_question');
$csvData = $csvModel->field('question,answer_A,answer_B,answer_C,answer_D,true_answer')->select();
$str = "题目,答案A,答案B,答案C,答案D,正确答案\n";
$str = iconv('utf-8', 'gb2312', $str);
foreach ($csvData as $item) {
$question = iconv('utf-8', 'gb2312', $item['question']);
$a = iconv('utf-8', 'gb2312', $item['answer_a']);
$b = iconv('utf-8', 'gb2312', $item['answer_b']);
$c = iconv('utf-8', 'gb2312', $item['answer_c']);
$d = iconv('utf-8', 'gb2312', $item['answer_d']);
$t = iconv('utf-8', 'gb2312', $item['true_answer']);
$str .= $question . "," . $a . "," . $b . "," . $c . "," . $d . "," . $t . "\n";
}
$filename = '选择题.csv';
$this->export_filename($filename, $str);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

请求头导出方法

public function export_filename($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;
}


来源:http://blog.csdn.net/a2824256/article/details/53897844
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: