103 lines
2.4 KiB
PHP
103 lines
2.4 KiB
PHP
<?php
|
|
class CSVWriter
|
|
{
|
|
const ON_DISK = 0;
|
|
const FOR_DOWNLOAD = 1;
|
|
|
|
private $file_path;
|
|
private $buffer;
|
|
private $header = null;
|
|
private $footer = null;
|
|
private $lines = array();
|
|
|
|
function __construct($file_path)
|
|
{
|
|
$this->file_path = $file_path;
|
|
}
|
|
|
|
function setHeader(array $line)
|
|
{
|
|
$this->header = $line;
|
|
return $this;
|
|
}
|
|
|
|
function addLine(array $line)
|
|
{
|
|
$this->lines[] = $line;
|
|
return $this;
|
|
}
|
|
|
|
function setFooter(array $line)
|
|
{
|
|
$this->footer = $line;
|
|
return $this;
|
|
}
|
|
|
|
function sortBy($index_column, $ascendant=true)
|
|
{
|
|
usort($this->lines,
|
|
function(array $a, array $b) use ($index_column, $ascendant) {
|
|
if ($a[$index_column] < $b[$index_column]) {
|
|
return $ascendant?-1:1;
|
|
}
|
|
else if ($a[$index_column] > $b[$index_column]) {
|
|
return $ascendant?1:-1;
|
|
}
|
|
else {
|
|
return 0;
|
|
}
|
|
});
|
|
return $this;
|
|
}
|
|
|
|
function flush($type = self::FOR_DOWNLOAD)
|
|
{
|
|
$output = fopen('php://output', 'w');
|
|
|
|
ob_start();
|
|
|
|
if (is_array($this->header)) {
|
|
fwrite($output, '"'.implode('","', $this->header).'"'.PHP_EOL);
|
|
}
|
|
|
|
foreach($this->lines as $line) {
|
|
fwrite($output, '"'.implode('","', $line).'"'.PHP_EOL);
|
|
}
|
|
|
|
if (is_array($this->footer)) {
|
|
fwrite($output, '"'.implode('","', $this->footer).'"'.PHP_EOL);
|
|
}
|
|
|
|
$this->buffer = ob_get_clean();
|
|
|
|
if ($type == self::FOR_DOWNLOAD) {
|
|
$this->outputForDownload();
|
|
}
|
|
else {
|
|
$this->save();
|
|
}
|
|
return $this;
|
|
}
|
|
|
|
private function outputForDownload()
|
|
{
|
|
header("Pragma: public");
|
|
header("Expires: 0");
|
|
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
|
|
header("Cache-Control: private",false);
|
|
header("Content-Type: text/csv");
|
|
header("Content-Disposition: attachment; filename=\"".basename($this->file_path)."\";" );
|
|
header("Content-Transfer-Encoding: binary");
|
|
exit($this->buffer);
|
|
}
|
|
|
|
private function save()
|
|
{
|
|
$f = fopen($this->file_path, 'w');
|
|
if ($f) {
|
|
fwrite($f, $this->buffer);
|
|
fclose($f);
|
|
}
|
|
}
|
|
}
|