博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

php 导出csv文件

Posted on 2016-04-28 16:31  红与黑hyh  阅读(156)  评论(0编辑  收藏  举报
<?php

 $sql = "select * from members_sqzj order by id asc";
            $result = $db->fetch_All($sql);//查询数据

            $str = "name,tel,company,shangquan\n";
            $str = iconv('utf-8','gb2312',$str);
            foreach($result as $k=>$v){
                $name = iconv('utf-8','gb2312',$v['name']); //中文转码
                $tel = iconv('utf-8','gb2312',$v['tel']);
                $company = iconv('utf-8','gb2312',$v['company']);
                $shangquan = str_replace(',','|',$v['shangquan']);//不能出现“,”
                $shangquan = iconv('utf-8','gb2312',$shangquan);
                $str .= $name.",".$tel.",".$company.",".$shangquan."\n"; //用引文逗号分开
            }
            $filename = date('Ymd').'.csv'; //设置文件名
            export_csv($filename,$str); //导出


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;
}
?>        

  代码简单,header不好记。