public function setCsvContent($rows, $attachmentName, $columns = null)
{
if (is_string($columns)) {
$columns = explode(',', $columns);
}
if (pathinfo($attachmentName, PATHINFO_EXTENSION) !== 'csv') {
$attachmentName .= '.csv';
}
$this->setAttachment($attachmentName);
$file = fopen('php://temp', 'r+');
fprintf($file, "");
if ($columns !== null) {
if (Text::startsWith($columns[0], 'ID')) {
$columns[0] = strtolower($columns[0]);
}
fputcsv($file, $columns);
}
foreach ($rows as $row) {
if (is_object($row)) {
if (method_exists($row, 'toArray')) {
$data = $row->toArray();
} else {
$data = (array) $row;
}
} elseif (!is_array($row)) {
$data = [$row];
} else {
$data = $row;
}
fputcsv($file, $data);
}
rewind($file);
$content = stream_get_contents($file);
fclose($file);
$this->setContentType('text/csv');
$this->setContent($content);
return $this;
}