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

来源:互联网 发布:打开windows资源管理器 编辑:程序博客网 时间:2024/06/08 07:44

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

原创粉丝点击