为什么要用csv数据格式?
CSV与Excel(.xls) - 有什么区别?
https://www.guru99.com/excel-vs-csv.html
csv导出数据,下载存储到默认地址文件 和 另存为新的目录地址 的简单处理。
1.准备数据
2.拼接文本标题
3.拼接文本内容
4.整个数据内容
6.写入文件
7、下载方式的选择(默认地址?or 另存为?)
if (isset($_GET['action']) && $_GET['action'] == 'make'){ $fp = @fopen("demo_csv.csv","a"); //打开csv文件,如果不存在则创建 $datas = Array( array( 'time' => '2015-12-05 15:45:52.2400', 'vname' => '客人1', 'type' => '发票业务咨询', 'msg' => '账号未注销admi"n"的内"部12'."\n"."123"."\n\r"."3323" ), array( 'time' => '2015-12-05 15:45:52.2400', 'vname' => '客人2', 'type' => '订单业务咨询', 'msg' => '週日24:00admin"的"内部"12'."\n"."123"."\n\r"."3323" ) ); $title_new = Array('时间','用户名称','咨询类型','聊天记录'); $fields = Array('time','vname','type','msg'); $title = ''; $strs = ''; //循环获取excel标题 foreach ($title_new as $title_t) { $title = $title.",".$title_t; } //循环获取excel每行内容 foreach ($datas as $k=>$data) { $str =''; foreach ($fields as $field) { $data[$field]=str_replace("\"","'",$data[$field]); $str=$str.',"'.$data[$field].'"'; } $strs=$strs.substr($str,1)."\n"; unset($str); } $title = substr($title,1); $data_str = $title."\n".$strs; //$data_str = iconv("utf-8","gb2312//IGNORE",$data_str); $data_str = mb_convert_encoding($data_str, "GBK", "UTF-8"); export_csv('11.csv', $data_str);die; if(!fputs($fp,$data_str)){ echo '写入文件失败~'; } else{ echo '写入文件成功~'; } fclose($fp); //关闭文件句柄 } echo "<br>"; echo "<a href='?action=make'>生成csv文件</a>"; function export_csv($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;exit; }
写入到默认地址,注释 export_csv('11.csv', $data_str);die; 该行内容即可。
本文为崔凯原创文章,转载无需和我联系,但请注明来自冷暖自知一抹茶ckhttp://www.cksite.cn