Last active
January 12, 2019 00:27
-
-
Save OrderAndCh4oS/ebf05ae1355eb594cf54b3c1efb22173 to your computer and use it in GitHub Desktop.
CSV Download
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Author
OrderAndCh4oS
commented
Jan 11, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment