PHP导出CSV案列
更新:HHH   时间:2023-1-7


$data = array();
$data = $app->getStatisApp(2,$username,$whereDepartment,$status,$level,$time);
$str = mb_convert_encoding ("姓名,一级部门,所在部门,直属上级,入职时间\n", 'GBK', 'UTF8' );
$filename = "转正申请表审核进度统计";
$filename = mb_convert_encoding ( $filename, 'GBK', 'UTF8' );
ob_end_clean ();
header ( "HTTP/1.1 200 OK" );
header ( 'Content-Encoding: none' );
header ( 'Content-type:text/csv' );
header ( "Content-Disposition:p_w_upload;filename={$filename}.csv" );
header ( 'Cache-Control:must-revalidate,post-check=0,pre-check=0,max-age=31536000' );
header ( 'Expires:0' );
header ( 'Pragma:public' );
foreach ( $data as $value ) {
    $str .= mb_convert_encoding ( "{$value['truename']},{$value['oneDepartment']},{$value['twoDepartment']},{$value['leaderTruename']},{$value['entry_time']},{$value['formal_time']}\n", 'GBK', 'UTF8');
}
echo $str;


解决内容中含有''','"'字符

     foreach ($data as $row) {
                $str_arr = array();
                foreach ($row as $column) {
                    $column = mb_convert_encoding($column,'GBK', 'UTF8');
                    $str_arr[] = '"' . str_replace('"', '""', $column) . '"';
                }
                $str.=implode(',', $str_arr) . PHP_EOL;
       }


原文:http://www.cnblogs.com/mybest/archive/2012/11/14/2770635.html

当内容中含有',' '"'的处理方式

/**
 * 生成默认以逗号分隔的CSV文件
 * 解决:内容中包含逗号(,)、双引号("")
 * @author zf
 * @version 2012-11-14
 */
header("Content-Type: application/vnd.ms-excel; charset=GB2312");
header("Content-Disposition: p_w_upload;filename=CSV数据.csv ");
$rs = array(
    array('aa', "I'm li lei", '"boy"', '¥122,300.00'),
    array('cc', 'I\'m han mei', '"gile"', '¥122,500.00'),
);
$str = '';
foreach ($rs as $row) {
    $str_arr = array();
    foreach ($row as $column) {
        $str_arr[] = '"' . str_replace('"', '""', $column) . '"';
    }
    $str.=implode(',', $str_arr) . PHP_EOL;
}
echo $str;

返回web开发教程...