PHP导出文件到csv函数

PHP导出文件到CSV函数

function exportCSV($data=array(),$title=array(),$filename)
    {
        $encoded_filename = urlencode($filename);
        header('Content-Type: application/vnd.ms-excel');   //header设置
        $ua = $_SERVER["HTTP_USER_AGENT"];
        if(preg_match("/MSIE/", $ua)) {
              header('Content-Disposition: attachment; filename="' . $encoded_filename . '.csv"');
        } else if (preg_match("/Firefox/", $ua)) {
              header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '.csv"');
        } else {
              header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
        }
        
        header('Cache-Control: max-age=0');
    
        $fp = fopen('php://output','a');    
    
        foreach($title as $k=>$v){
            $title[$k]=iconv("UTF-8", "GB2312",$v);
        }
        fputcsv($fp,$title);  
    
        if (!empty($data)){
            foreach($data as $key=>$val){
                foreach ($val as $ck => &$cv) {
                    //$data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
                    $val[$ck]= mb_convert_encoding($cv, "GBK", "UTF-8");
                }
                fputcsv($fp,$val);
                $data[$key]=implode("\t", $data[$key]);
            }
        } 
        
        exit;  //记得加这个,不然会跳转到某个页面。
     
    
    }

用法

$list=array(0=>array('1','5.3数学练习册',
            1=>array('2','5.3数学练习册'), 
2=>array('3','5.3数学练习册',);
$title = array('序号', '练习册名称'); //设置要导出excel的表头 
exportCSV($list,$title,1);

 

你可能感兴趣的:(PHP导出文件到csv函数)