Skip to content

Instantly share code, notes, and snippets.

@OrderAndCh4oS
Last active January 12, 2019 00:27
Show Gist options
  • Save OrderAndCh4oS/ebf05ae1355eb594cf54b3c1efb22173 to your computer and use it in GitHub Desktop.
Save OrderAndCh4oS/ebf05ae1355eb594cf54b3c1efb22173 to your computer and use it in GitHub Desktop.
CSV Download
<?php
/**
* Class CSVDownload
*/
class CSVDownload {
/**
* @var array
*/
private $headers;
/**
* @var array
*/
private $rows;
/**
* @var string
*/
private $filename;
/**
* CSVDownload constructor.
* @param array $headers
* @param array $rows
* @param string $filename
*/
function __construct(
array $headers,
array $rows,
string $filename
) {
$this->headers = $headers;
$this->rows = $rows;
$this->filename = $filename;
}
/**
* @param $array
* @param $key
* @return string
*/
private function getKeyValueOrEmptyString($array, $key) {
return array_key_exists($key, $array) ? $array[$key] : '';
}
/**
* @param $row
* @return array
*/
private function rowToArray($row): array
{
$array = [];
foreach ($this->headers as $key) {
$array[] = $this->getKeyValueOrEmptyString($row, $key);
}
return $array;
}
/**
* @return false|string|null
*/
private function createCSV()
{
if (count($this->rows) === 0) {
return null;
}
ob_start();
$df = fopen("php://output", 'w');
fputcsv($df, $this->headers);
foreach ($this->rows as $row) {
fputcsv($df, $this->rowToArray($row));
}
fclose($df);
return ob_get_clean();
}
/**
* @throws Exception
*/
private function defineHeaders(): void
{
$now = new DateTime('now');
$filename = $this->filename . $now->format('T') . '.csv';
header("Expires: 0");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: ".$now->format("D, d M Y H:i:s")." GMT");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
}
public function download() {
$this->defineHeaders();
echo $this->createCSV();
exit;
}
}
@OrderAndCh4oS
Copy link
Author

<?php
$csv = new CSVDownload(['title', 'author'], [
    ['title' => 'Moby Dick', 'author' => 'Herman Melville'],
    ['title' => '1984', 'author' => 'George Orwell']
], 'books');

$csv->download();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment