Skip to content

Instantly share code, notes, and snippets.

@twaddington
Created June 3, 2011 07:54
Show Gist options
  • Save twaddington/1006027 to your computer and use it in GitHub Desktop.
Save twaddington/1006027 to your computer and use it in GitHub Desktop.
Basic class for serializing PHP arrays in a csv format.
<?php
class CSV {
protected $data;
/*
* @params array $columns
* @returns void
*/
public function __construct($columns) {
$this->data = '"' . implode('","', $columns) . '"' . "\n";
}
/*
* @params array $row
* @returns void
*/
public function addRow($row) {
$this->data .= '"' . implode('","', $row) . '"' . "\n";
}
/*
* @returns void
*/
public function export($filename) {
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
echo $this->data;
die();
}
public function __toString() {
return $this->data;
}
}
$csv = new CSV(array('date', 'name', 'address'));
$csv->addRow(array('2/2/2010', 'John', 'Portland, OR'));
// export csv as a download
$filename = 'names';
$csv->export($filename);
// *or* pass the csv data to a variable as a string
$string = $csv;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment