Writing Arrays to CSV or Other Delimited Files

Often, in the past when I wanted to write data to a file I would load up and array, iterate over it, and then insert tab and new line breaks so that I could create a CSV. Well, those days are long gone now that PHP5 has included this awesome and useful function fputcsv(). It takes an array as an input and then does the iterations an string manipulation and creates a CSV file. One can also specify the delimiter of the file as well as the field enclosure. To see more documentation click here.

This example simply takes the array and writes it to a CSV file:

//Example array
$info = array(1, 2, 3, 4, 5); 

//Open a new file
$filehandler = fopen("test.csv", "w");

//Call the fputcsv method
fputcsv($filehandler, $info);