3

I am using fputcsv function to export data as CSV file but it is displaying all data in browser instead of downloading this as CSV file. Here is my code

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=export.csv');
$output = fopen('php://output', 'w');
fputcsv($output, $column_headings);
fclose($output);

Data is displaying correctly in browser but I want to download this as export.csv file.I do not know what is wrong with this. Any suggestion regarding this will be appreciated.

wplearner
  • 405
  • 6
  • 19

2 Answers2

1

You cannot control how the browser handles the text/csv content type, however, you can tell the browser it should treat the data as binary.

header('Content-Type: application/octet-stream');

Alex Barker
  • 4,316
  • 4
  • 28
  • 47
  • Thanks for your answer and I replace header('Content-Type: text/csv; charset=utf-8'); with header('Content-Type: binary/octet-stream'); but it did not work. – wplearner Jan 21 '20 at 16:45
  • Try application/octet-stream; – Alex Barker Jan 21 '20 at 16:51
  • If it is still displaying, then either something is wrong with your content-type header or browser. Double check your headers in the developer console and make sure the content type is what you think it is, and if it is opening in a different program other than the browser, this is the intended behavior for your configuration. – Alex Barker Jan 21 '20 at 17:21
1

I added ob_start(); at the start of my file and now I can export files.

wplearner
  • 405
  • 6
  • 19