3

I need to export a .csv file with php. I used below code to do that:

header('Content-Encoding: UTF-8');
header('Content-type: application/csv; charset=UTF-8');
header("Content-Disposition: attachment; filename=$fn");
echo "\xEF\xBB\xBF"; // UTF-8 BOM
print($csv); 

$csv contains some persian characters. When i opened the exported file with ms excel, wrong characters showed. When i opened file with notepad characters showed right. how can i solve this problem?

6
  • is your original content in utf8? if you use utf8_encode on your $csv does that help? Commented Apr 28, 2012 at 7:25
  • Original content is in utf8. But i did not use any tag in php file for defining that, like [<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />] Commented Apr 28, 2012 at 7:33
  • You may want to test that. I've had problems in the past with such. At all points it should be in utf8 (ie. your database you are loading it from). Also reading this drupal.org/node/172996 seems it could be an inherent problem with csv files; one person suggests saving as .txt and opening the .txt as a csv in excel since .txt supports utf8 and csv only ascii Commented Apr 28, 2012 at 7:37
  • Excel is just notoriously bad at importing "weird" (in large quotes) encodings. Try its File > Import functions, not the regular double click. Commented Apr 28, 2012 at 7:58
  • 1
    you could try writing xlsx instead Commented Apr 28, 2012 at 8:24

1 Answer 1

2

Here's how I did it.

header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
header('Content-Transfer-Encoding: binary');
echo "\xEF\xBB\xBF";

Earlier i was getting garbage characters now correct data is exported.

Sign up to request clarification or add additional context in comments.

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.