public function to_csv($data = NULL, $delimiter = ',', $enclosure = '"')
{
// Use a threshold of 1 MB (1024 * 1024)
$handle = fopen('php://temp/maxmemory:1048576', 'w');
if ($handle === FALSE) {
return NULL;
}
// If no data is passed as a parameter, then use the data passed
// via the constructor
if ($data === NULL && func_num_args() === 0) {
$data = $this->_data;
}
// If NULL, then set as the default delimiter
if ($delimiter === NULL) {
$delimiter = ',';
}
// If NULL, then set as the default enclosure
if ($enclosure === NULL) {
$enclosure = '"';
}
// Cast as an array if not already
if (is_array($data) === FALSE) {
$data = (array) $data;
}
// Check if it's a multi-dimensional array
if (isset($data[0]) && count($data) !== count($data, COUNT_RECURSIVE)) {
// Multi-dimensional array
$headings = array_keys($data[0]);
} else {
// Single array
$headings = array_keys($data);
$data = [$data];
}
// Apply the headings
fputcsv($handle, $headings, $delimiter, $enclosure);
foreach ($data as $record) {
// If the record is not an array, then break. This is because the 2nd param of
// fputcsv() should be an array
if (is_array($record) === FALSE) {
break;
}
// Suppressing the "array to string conversion" notice.
// Keep the "evil" @ here.
$record = @array_map('strval', $record);
// Returns the length of the string written or FALSE
fputcsv($handle, $record, $delimiter, $enclosure);
}
// Reset the file pointer
rewind($handle);
// Retrieve the csv contents
$csv = stream_get_contents($handle);
// Close the handle
fclose($handle);
return $csv;
}