[PHP] 匯出處理 – CSV、EXCEL匯出實例教學

以CSV為例,PHP的Header與輸出如下:

header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=$filename");
echo $content;
exit;

檔案格式介紹:

格式 Type 相隔符號
CSV text/x-csv ,
SXW application/octet-stream \t
Word application/msword
Excel application/vnd.ms-excel

編碼轉換:

(1) iconv ( “原編碼” , “新編碼” , “內容” );

echo iconv( "UTF-8", "Big5" , $content);

(2) mb_convert_encoding( “內容” , “新編碼” , “原編碼”);

echo mb_convert_encoding($content , "Big5" , "UTF-8");

實作範例:

CSV (using ,)

<?php 
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=output.csv");
$content = "Column1,tColumn2\nnRow1-1,nRow1-2";
$content = mb_convert_encoding($content , "Big5" , "UTF-8");
echo $content;
exit;
?>

CSV不想硬刻的話可以使用fputcsv()
完整CSV Helper可以參考:https://github.com/yidas/php-helpers/blob/master/src/CSV.php (包含過濾)

EXCEL (using \t)

<?php 
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=exportFileName.xls");
$content = "Column1\tColumn2\tColumn3\nRow1-1\tRow1-2\tRow1-3";
$content = mb_convert_encoding($content , "Big5" , "UTF-8");
echo $content;
exit;
?>

\n: 共用換行; ,: CSV分隔號; \t: XLS分隔號

Leave a Reply

Your email address will not be published. Required fields are marked *