PHP数据转csv格式的excle

2018-09-12T10:15:00
<?php 
/**
 * 数据转csv格式的excle
 * @param  array $data      需要转的数组
 * @param  string $header   要生成的excel表头
 * @param  string $filename 生成的excel文件名
 * 示例数组:
$data = array(
'1,2,3,4,5',
'6,7,8,9,0',
'1,3,5,6,7'
);
$header='用户名,密码,头像,性别,手机号';
 */
function create_csv($data,$header=null,$filename='simple.csv'){
    // 如果手动设置表头;则放在第一行
    if (!is_null($header)) {
        array_unshift($data,&nbsp;$header);
    }
    // 防止没有添加文件后缀
    $filename=str_replace(&#39;.csv&#39;,&nbsp;&#39;&#39;,&nbsp;$filename).'.csv';
    ob_clean();
    Header( "Content-type:  application/octet-stream ");
    Header( "Accept-Ranges:  bytes ");
    Header( "Content-Disposition:  attachment;  filename=".$filename);
    foreach( $data&nbsp;as&nbsp;$k => $v){
        // 如果是二维数组;转成一维
        if (is_array($v)) {
            $v=implode(&#39;,&#39;,&nbsp;$v);
        }
        // 替换掉换行
        $v=preg_replace(&#39;/\s*/&#39;,&nbsp;&#39;&#39;,&nbsp;$v);
        // 解决导出的数字会显示成科学计数法的问题
        $v=str_replace(&#39;,&#39;,&nbsp;&quot;\t,&quot;,&nbsp;$v);
        // 转成gbk以兼容office乱码的问题
        echo iconv('UTF-8','GBK',$v)."trn";
    }
}
?>
当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »