使用php导出为UTF-8 for Excel的CSV

时间:2016-04-20 09:24:40

标签: php mysql csv utf-8

Below are my code used to generate csv file. 
My problem is UTF-8 characters  are not coming correctly.
even I tried iconv also, but  no result.

PHP CODE
-----------------
  

$ con = mysql_connect('localhost','root','');       $ db_selected = mysql_select_db('test',$ con);       mysql_query(“SET NAMES utf8”);       $ qry_res = mysql_query(“SELECT * FROM table 2”);

$filename = "test.csv";
$fp = fopen('php://output', 'w');
//$header = array('id','name');
$header = array("Id","Name");
header('Content-type: application/csv;charset=utf-8');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);

while($data = mysql_fetch_row($qry_res)){
  fputcsv($fp, $data);
}

 exit;
------------------------------------------
Table value:
-----------------------
Id  Name
2   traducción de idiomas
3   תרגום שפות
4   language translation
7   Tłumaczenie na język

Result:
Id  Name
2   traducción de idiomas
3   ????? ????
4   language translation 
7   T?umaczenie na j?zyk

Thanks in advance.

2 个答案:

答案 0 :(得分:3)

尝试在标题后添加以下内容:

echo "\xEF\xBB\xBF";  // BOM header UTF-8

答案 1 :(得分:0)

如果原始数据为UTF-8,则将数据导出为CSV / Excel可读的最佳方法是转换数据。

$chain1 = iconv("UTF-8", "ISO-8859-15", 'érase camión del niño'); 
$chain2 = iconv("UTF-8", "cp1252", 'érase camión del niño'); 
echo $chain1.$chain2;

对我有用。