1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class CSV
{
private $headers;
private $file_name;
private $delimiter;
private $enclosure;
private $handle;
public function __construct($delimiter = ';', $enclosure = '"')
{
$this->handle = fopen('php://memory', 'rb+');
$this->delimiter = $delimiter;
$this->enclosure = $enclosure;
}
public function headers(array $headers)
{
$this->headers = $headers;
return $this;
}
public function insert(array $fields)
{
fputcsv($this->handle, $fields, $this->delimiter, $this->enclosure);
return $this;
}
public function output($file_name = 'temp.csv')
{
header("Content-type: text/csv");
header("Content-Disposition: attachment;filename=$file_name");
if (!empty($this->headers)) {
$header = fopen('php://output', 'rb+');
fputcsv($header, $this->headers, $this->delimiter, $this->enclosure);
}
rewind($this->handle);
fpassthru($this->handle);
exit;
}
} |