php導出數組到csv格式demo


php的二維數組導出到csv需要處理文字編碼,代碼如下

<?php
$data=array(
    array("username"=>"test1","password"=>"123"),
    array("username"=>"test2","password"=>"456"),
    array("username"=>"test3","password"=>"789"),
);
export_csv($data);
function export_csv($data)
{
    $string="";
    foreach ($data as $key => $value) 
    {
        foreach ($value as $k => $val)
        {
            $value[$k]=iconv('utf-8','gb2312',$value[$k]);
        }

        $string .= implode(",",$value)."\n"; //用英文逗號分開 
    }
    $filename = date('Ymd').'.csv'; //設置文件名
    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 $string; 
}
?>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM