PHP: Download an array as a CSV file


Often it is necessary or useful to output an array of data in PHP as a CSV file. The below script will take a 2 dimensional array and output a CSV file. Internal arrays must have the same keys. These keys may be set to null, but the key must exist. Below is a sample array that we can work with through this example.

Add the code as follows

Once the CSV is generated, it will be downloaded. This is what the CSV file will look like:

Leave a Reply

Your email address will not be published. Required fields are marked *