Generate CSV file from a PHP array

Submitted by:Jhon Brain

Date added:05 December, 2012

Category:PHP

The function accept 3 parameters: the data, the csv delimeter (default is a comma) and the csv enclosure (default is a double quote).

Tags: generate csv

Code Snippet:

function generateCsv($data, $delimiter = ',', $enclosure = '"') {
$handle = fopen('php://temp', 'r+');
foreach ($data as $line) {
fputcsv($handle, $line, $delimiter, $enclosure);
}
rewind($handle);
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
return $contents;
}
 
 

Comments