Thursday, 9 August 2018

Creating A CSV File With PHP

This a short tutorial on how to create a CSV file with PHP. I will also show you how to “force it” to download as a file (this is extremely handy for creating “Export to CSV” buttons and whatnot).
Let’s take a look at the following code example (each line is explained in the comments):
Here are the steps that we took:
  1. We gave our CSV file a name. This is the name that the file will have when the user downloads it (you could append a timestamp on to it, just to keep it unique).
  2. We set our Content-Type and Content-Disposition headers. These headers allow us to force the user’s browser into downloading the file.
  3. We setup a multidimensional array for our CSV data. This array should be an array that consists of arrays. Each array inside the $data array represents a row in our CSV file. The elements inside these arrays represents a column. If you look at the code above, you’ll see that I went with an extremely simple example of 4 rows and 2 columns. Be sure to change this around a bit, just to get your head around it.
  4. We opened up a PHP output stream.
  5. We looped through the $data array. Inside the loop, we write each row to the output stream by using the function fputcsv.
  6. Finally, we close the file handle (in this case, it’s our PHP output stream).
If you navigate to this script on your server, you’ll see that a CSV file is automatically downloaded and that it contains the test data from our array.

0 comments:

Post a Comment