generator = $generator; $this->delimiter = $delimiter; $this->enclosure = $enclosure; } /** * @return string */ public function export() { $this->sendHeaders('export.csv'); $this->echoContent(); } protected function sendHeaders($fileName = null) { if ($fileName === null) { $fileName = (string)time(); } while (ob_get_level() > 0) { ob_end_flush(); } header('Content-Type: text/plain; charset=UTF-8'); header('Content-Disposition: attachment; fileName="' . $fileName . '"'); } private function echoContent() { $out = fopen('php://output', 'wb'); if (false === $out) { throw new \RuntimeException('Can not open stdout for writing'); } foreach ($this->generator->fetch() as $row) { if (!empty($row)) { $result = fputcsv($out, $row, $this->delimiter, $this->enclosure); if (false === $result) { throw new \RuntimeException('Can not write to stdout'); } } } fclose($out); } }