Skip to content

Instantly share code, notes, and snippets.

@macedd
Last active August 29, 2015 14:16
Show Gist options
  • Save macedd/1f6fa300994ffb9ec18b to your computer and use it in GitHub Desktop.
Save macedd/1f6fa300994ffb9ec18b to your computer and use it in GitHub Desktop.
Large Dataset Csv Writer Class
<?php
class Csv_Writer
{
public $stream, $wrote = false;
function __construct() {
header( 'Content-Type: text/csv' );
$this->stream = fopen('php://output', 'w');
}
function write($data)
{
if (!$this->wrote) {
$keys = array_keys($data[0]);
fputcsv($this->stream, $keys);
$this->wrote = true;
}
foreach ($data as $row)
fputcsv($this->stream, $row);
fflush($this->stream);
}
function end() {
if ($this->stream)
fclose($this->stream);
}
function __destruct() {
$this->end();
}
}
$csv = new Csv_Writer();
foreach($pages as $page_number) {
$result = Model::load($page_number);
$csv->write($result);
}
$csv->end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment