php array to csv create code example
Example 1: php array to csv
Instead of writing out values consider using 'fputcsv()'.
This may solve your problem immediately.
function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
$f = fopen('php://memory', 'r+');
foreach ($data as $item) {
fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
}
rewind($f);
return stream_get_contents($f);
}
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));
Example 2: php array to csv string
To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on failure.
Syntax :
fputcsv( file, fields, separator, enclosure, escape )
Example:
<?php
$list = array(
['Name', 'age', 'Gender'],
['Bob', 20, 'Male'],
['John', 25, 'Male'],
['Jessica', 30, 'Female']
);
$fp = fopen('persons.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>