Create and download CSV files using PHP

If you need to download a CSV file on the fly without writing to external file, than you need to open php://output stream and use fputcsv() on it.

Built in fputcsv() will generate CSV lines from given array, so you will have to loop over and collect the lines.

And you need to use some special headers , those headers tell to the browser that the content you are going to send must be downloaded instead, as displayed on the browser as a regular HTML.

Below is the simple function which will generate and output the CSV file on the fly

How to Use

Just call the function with array as the first parameter and second parameters is file name and it is optional.

Function refernce

  • fputcsv() — Format line as CSV and write to file pointer
  • fopen() — Opens file or URL
  • foreach() — Format line as CSV and write to file pointer
  • fclose() — Closes an open file pointer

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.