简体   繁体   中英

Export to CSV in UTF-8 for Excel using php

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.

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

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

If you origin data are UTF-8, the best way to export data to CSV / Excel readable, is to converter your data.

$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;

That worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM