A comma-separated values (CSV) file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. The following PHP function takes an array and either returns the data to a screen or writes the array contents as a CSV file. The non-standard implementation of the CSV format means you may have to play around with the output.
PHP Function
1
<?php
2
/*
3
Create CSV File From Array With PHP
4
http://www.beliefmedia.com/code/php-snippets/csv-array-php
5
*/
6
7
function beliefmedia_csv_array($data, $file = false, $delimiter = ',', $enclosure = '"') {
8
9
10
11
rewind($handle);
12
13
fclose($handle);
14
15
/* Either return to screen or write to file */
16
if ($file === false) return $contents;
17
18
}
Sample use is as follows:
If you're looking for a more robust solution there's plenty of CSV libraries available to handle more complex requirements.