iT邦幫忙

0

php匯出csv檔 中文亂碼問題

  • 分享至 

  • xImage

想請問我想要匯出csv檔但匯出的檔案一直出現亂碼...

<form action="export.php" method="post">
    <input type="submit" name="export" value="匯出資料" class="btn-small-blue-style">
</form>

有加了這段程式碼echo "\xEF\xBB\xBF";
但匯出的資料中文還是亂碼,
想請問應該如何解決?

下面是export.php

if (isset($_POST["export"])) {
	header('Content-Type: text/csv; charset=utf-8');
	header('Content-Disposition: attachment; filename=data.csv');
	echo "\xEF\xBB\xBF";
	$output = fopen("php://output", "a");
	fputcsv($output, array('給號時間', '訂單編號', '委刊單編號', '廣告主', '活動名稱', '委刊公司', '行業別', '組別', '負責業務', '預算', '計價方式'));
}
rogeryao iT邦超人 8 級 ‧ 2021-05-22 00:05:47 檢舉
結案率 : 1/12 ,等有緣人幫你吧。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
japhenchen
iT邦超人 1 級 ‧ 2021-05-22 10:34:16
最佳解答

SORRY更正我的做法,這就正常了

<?php
setlocale(LC_ALL,'zh_TW');
header('Content-Type: text/csv;');
header('Content-Disposition: attachment; filename=data.csv');    
$a=array('給號時間', '訂單編號', '委刊單編號', '廣告主', '活動名稱', '委刊公司', '行業別', '組別', '負責業務', '預算', '計價方式');
echo iconv("UTF-8","big5",preg_replace("/[\[\]\"]/","", json_encode($a,JSON_UNESCAPED_UNICODE)));

https://ithelp.ithome.com.tw/upload/images/20210522/20117954VSioALXTUP.png

看更多先前的回應...收起先前的回應...

已更正

下載CSV測試點 http://music.mihodb.com/tts/test.php

程式內容縮排一下比較好理解

<?php
setlocale(LC_ALL,'zh_TW');
header('Content-Type: text/csv;');
header('Content-Disposition: attachment; filename=data.csv');    
$a=array('給號時間', '訂單編號', '委刊單編號', '廣告主', '活動名稱', '委刊公司', '行業別', '組別', '負責業務', '預算', '計價方式');
echo 
    iconv("UTF-8","big5",
        preg_replace("/[\[\]\"]/","", 
            json_encode(
                $a,
                JSON_UNESCAPED_UNICODE
            )
        )
    );

小魚 iT邦大師 1 級 ‧ 2021-05-22 14:59:27 檢舉

簡單來說就是轉成Big5, 前提是客戶是使用繁體中文的.

json是轉成純字串比較好理解的做法,因為不知道php的fputcsv會不會做編碼的動作

謝謝!!

0
墨嗓
iT邦研究生 4 級 ‧ 2021-05-22 02:14:36

如果是CSV的話,還要看你用什麼工具打開。

你可以先用文字編輯器,開啟看看,內容是不是已經如你說的輸出是 UTF-8 了。

接著是開啟 CSV 檔的軟體,Microsoft Excel 並不是所有版本都直接支援 utf-8 格式的 csv 檔案。

我要發表回答

立即登入回答