Generate CSV From PHP Array

There are a few options that you can pass in through the $args array:

  • download – If set as a string ending in ".csv" a file of this name will be downloaded. If set to TRUE, a file named download.csv will be downloaded. If FALSE (default), the CSV will be printed on the screen.
  • line_breaks – If set to "windows" then \r\n will be used instead of Unix's \n to indicate line breaks at the end of rows.
  • trim – If set to TRUE, the values (and column names) will have extra spaces removed by PHP's built-in trim function.

Now, here's the function itself:


// Array to CSV Function
// Copyright (c) 2014-2016, Ink Plant
// last updated May 10, 2016

function array_to_csv($data,$args=false) {
	if (!is_array($args)) { $args = array(); }
	foreach (array('download','line_breaks','return','trim') as $key) {
		if (array_key_exists($key,$args)) { $$key = $args[$key]; } else { $$key = false; }

	//for this to work, no output should be sent to the screen before this function is called
	if ($download) {
		if ((is_string($download)) && (substr($download,-4) == '.csv')) { $filename = $download; }
		else { $filename = 'download.csv'; }
		header('Content-Disposition:attachment; filename='.$filename);

	if ($line_breaks == 'windows') { $lb = "\r\n"; }
	else { $lb = "\n"; }

	//get rid of headers row, if it exists (headers should exist as keys)
	if (array_key_exists('headers',$data)) { unset($data['headers']); }

	$csv = '';
	$i = 0;
	foreach ($data as $row) {
		//display headers and save for later
		if ($i == 1) { 
			$c = '';
			$headers = array();
			foreach ($row as $key => $value) {
				$key = str_replace('"','""',$key);
				if ($trim) { $key = trim($key); }
				$csv .= $c.'"'.$key.'"'; $c = ',';
				$headers[] = $key;
			$csv .= $lb;

		//display values
		$c = '';
		foreach ($headers as $key) {
			$value = $row[$key];
			$value = str_replace('"','""',$value);
			if ($trim) { $value = trim($value); }
			$csv .= $c.'"'.$value.'"'; $c = ',';
		$csv .= $lb;

	$csv = trim($csv);

	if ($return) { return $csv; }
	else { echo $csv; }

	if ($download) { die(); }


So you can see how it works, we'll start with an example array of 2013 population estimates from the U.S. Census Bureau generated in our CSV to PHP Array article.


//set the location of your CSV file
$file = HOME_DIR.''; 

//turn that CSV file into an array ( see )
$data = csv_to_array($file,true);

//remove all but the 50 states
unset($data['2']); //U.S. total
unset($data['11']); //Washington, D.C.
unset($data['54']); //Puerto Rico

//remove everything except for state name and population estimates
foreach ($data as $i => $item) {
	foreach ($item as $key => $value) {
		if (!in_array($key,array('NAME','POPESTIMATE2013','POPEST18PLUS2013'))) { unset($data[$i][$key]); }

//set options for your CSV generation
$args = array(

//generate the csv and print it out to the screen
echo array_to_csv($data,$args);


Here's the CSV:

"New Hampshire","1323459","1052337"
"New Jersey","8899339","6877222"
"New Mexico","2085287","1577747"
"New York","19651127","15411151"
"North Carolina","9848060","7562455"
"North Dakota","723393","560705"
"Rhode Island","1051511","837524"
"South Carolina","4774839","3695041"
"South Dakota","844877","636918"
"West Virginia","1854304","1472626"

Combined with the CSV to Array function that goes the other way, this can be a handy way to quickly perform bulk operations on a CSV file and then save it again.



This post was first published on August 9th, 2014 and last updated on May 10th, 2015 by Robert James Reese in PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.