Created
June 3, 2011 07:54
-
-
Save twaddington/1006027 to your computer and use it in GitHub Desktop.
Basic class for serializing PHP arrays in a csv format.
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 { | |
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