4

Possible Duplicate:
Encoding a string as UTF-8 with BOM in PHP

i can export csv file from php with this code

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

$output = fopen('php://output', 'w');

but this code create file with charset utf-8 without BOM but i need charset utf-8.
is way for this problem?

Community
  • 1
  • 1
aya
  • 1,597
  • 4
  • 29
  • 59
  • Do you mean cvs or csv or both? – Jukka K. Korpela Dec 08 '12 at 06:15
  • excuse me file type is csv. – aya Dec 08 '12 at 06:43
  • Why do you need the BOM? As far as I know it's not recommended by the standard to include the byte order mark in Unicode. – Daniel Dec 08 '12 at 14:23
  • @Daniel I had the same problem with a Unicode CSV file - it opened fine in any text editor but trusty old Excel gets it wrong (at least on my machine) when the BOM isn't present. Maybe I'm doing something else wrong though! – OrganicPanda Jul 05 '13 at 08:44
  • @OrganicPanda That is because Microsoft office products default to windows operating system default (in sweden that is something like iso-8859-1) and does not even try to detect the file encoding. In my experience all windows products in the office suite has some serious issues with compatibility. I don't know how many hours I've spent on microsoft products alone to get exports and other documents for clients to work properly. It is scary since office suite is so widely used by professional businesses. – Daniel Jul 07 '13 at 20:18
  • 1
    @Daniel Thank you for the explanation. I need to support these crazy applications so I will continue to use the BOM and hope that it doesn't cause issues in other apps that are not expecting it! – OrganicPanda Jul 14 '13 at 08:05

1 Answers1

15

Here's how I did it.

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename=file.csv'));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
echo "\xEF\xBB\xBF"; // UTF-8 BOM
echo $csv_file_content;
exit();

Of course, you can substitute echo $csv_file_content with what you need.

bear
  • 11,364
  • 26
  • 77
  • 129
  • Thanks dude. It helped me. I knew it by using those \xEF\xBB\xBF will work out. But I dont know how to implement it. You made my day – Pavan Kumar Dec 15 '15 at 06:33
  • 1
    Just in case anyone else uses this solution, the line `header('Content-Disposition: attachment; filename=file.csv'));` in this code has an extra `)`, it should be: `header('Content-Disposition: attachment; filename=file.csv');` – webbm Apr 15 '18 at 19:30