Last active
August 29, 2015 14:16
-
-
Save macedd/1f6fa300994ffb9ec18b to your computer and use it in GitHub Desktop.
Large Dataset Csv Writer Class
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 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