Array to CSV

Posted on: June 19th, 2013 by admin No Comments

This is another useful function I often find myself needing:

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
function array_to_csv($array, $filename='data', $use_key=false, $delm=',', $return_data=false) {
	function maybeEncodeCSVField($string) {
	    if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
	        $string = '"' . str_replace('"', '""', $string) . '"';
	    }
	    return $string;
	}
	$csv = '';
	foreach($array as $row) {
		if($use_key) {
			foreach($row as $key => $value) {
				$csv .= '"'.make_pretty($key).'"'.$delm;
			}
			$use_key = false;
 
			$csv = substr($csv, 0, strlen($csv)-1);
			$csv .= PHP_EOL;
		}
		foreach($row as $key => $value) {
			$csv .= maybeEncodeCSVField($value).$delm;
		}
		$csv = substr($csv, 0, strlen($csv)-1);
		$csv .= PHP_EOL;
	}
	if($return_data) return $csv;
	header("Content-type: application/csv");
	header('Content-Disposition: attachment; filename="'.$filename.'.csv"');
	header("Pragma: no-cache");
	header("Expires: 0");
	die($csv);
}