Export data as a CSV with PHP

Export data as a CSV with PHP

This is a very simple class for constructing basic comma-separated value (CSV) files in PHP. The export method forces the correct headers to initiate a file download. More information can be had in the PHP documentation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?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;
 
?>

Leave a Reply