4
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
  • Not sure. Use Content-Type "text/csv;charset=UTF-8" as application means binary data without encoding. It seems the output encoding is single-byte Latin-1. And you might want to write at the beginning of the content a BOM for Unicode identification under Windows: U+FEFF, in java "\ufeff" forgotten about PHP. Commented Apr 20, 2016 at 9:37
  • Excel is notoriously bad when it comes to UTF-8; your best bet is to probably just generate a UTF-8 CSV file (which you appear to be doing) and then in Excel do a data import. You can then specify the character encoding of the file when you import it... or use something like Open Office. Commented Apr 20, 2016 at 9:44

3 Answers 3

14

Try to add following after your headers:

echo "\xEF\xBB\xBF";  // BOM header UTF-8
Sign up to request clarification or add additional context in comments.

3 Comments

Did you try it @Sakthi
It works fine.. Sorry for the late response Thank you.
Thanks for the reply. You might want to accept this as the correct answer, cheers
0

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.

Comments

0

Assuming your data is UTF in your DB, then you need to modify how you produce the document.

In my code I replace a bare echo with a modified one using iconv:

// echo $csv;

echo iconv("UTF-8", "ISO-8859-2", $csv);

Excel assumes ISO. An explicit instruction to dump it for UTF is what's required. Works for me every time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.