Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export to CSV in UTF-8 for Excel using php

Tags:

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.
like image 812
Sakthi Avatar asked Oct 16 '25 09:10

Sakthi


1 Answers

Try to add following after your headers:

echo "\xEF\xBB\xBF";  // BOM header UTF-8
like image 78
KiwiJuicer Avatar answered Oct 18 '25 21:10

KiwiJuicer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!