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:

1.   <?php
2.   
3.   // Array to CSV Function
4.   // Copyright (c) 2014-2016, Ink Plant
5.   // https://inkplant.com/code/array-to-csv
6.   // last updated May 10, 2016
7.   
8.   function array_to_csv($data,$args=false) {
9.   	if (!is_array($args)) { $args = array(); }
10.  	foreach (array('download','line_breaks','return','trim') as $key) {
11.  		if (array_key_exists($key,$args)) { $$key = $args[$key]; } else { $$key = false; }
12.  	}
13.  
14.  	//for this to work, no output should be sent to the screen before this function is called
15.  	if ($download) {
16.  		if ((is_string($download)) && (substr($download,-4) == '.csv')) { $filename = $download; }
17.  		else { $filename = 'download.csv'; }
18.  		header('Content-Type:text/csv');
19.  		header('Content-Disposition:attachment; filename='.$filename);
20.  	}
21.  
22.  	if ($line_breaks == 'windows') { $lb = "\r\n"; }
23.  	else { $lb = "\n"; }
24.  
25.  	//get rid of headers row, if it exists (headers should exist as keys)
26.  	if (array_key_exists('headers',$data)) { unset($data['headers']); }
27.  
28.  	$csv = '';
29.  	$i = 0;
30.  	foreach ($data as $row) {
31.  		$i++;
32.  		//display headers and save for later
33.  		if ($i == 1) { 
34.  			$c = '';
35.  			$headers = array();
36.  			foreach ($row as $key => $value) {
37.  				$key = str_replace('"','""',$key);
38.  				if ($trim) { $key = trim($key); }
39.  				$csv .= $c.'"'.$key.'"'; $c = ',';
40.  				$headers[] = $key;
41.  			}
42.  			$csv .= $lb;
43.  		}
44.  
45.  		//display values
46.  		$c = '';
47.  		foreach ($headers as $key) {
48.  			$value = $row[$key];
49.  			$value = str_replace('"','""',$value);
50.  			if ($trim) { $value = trim($value); }
51.  			$csv .= $c.'"'.$value.'"'; $c = ',';
52.  		}
53.  		$csv .= $lb;
54.  	}
55.  
56.  	$csv = trim($csv);
57.  
58.  	if ($return) { return $csv; }
59.  	else { echo $csv; }
60.  
61.  	if ($download) { die(); }
62.  }
63.  
64.  ?>

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.

1.   <?php
2.   
3.   //set the location of your CSV file
4.   $file = HOME_DIR.'inkplant.com/population.csv'; 
5.   
6.   //turn that CSV file into an array ( see https://inkplant.com/code/csv-to-array )
7.   $data = csv_to_array($file,true);
8.   
9.   //remove all but the 50 states
10.  unset($data['2']); //U.S. total
11.  unset($data['11']); //Washington, D.C.
12.  unset($data['54']); //Puerto Rico
13.  
14.  //remove everything except for state name and population estimates
15.  foreach ($data as $i => $item) {
16.  	foreach ($item as $key => $value) {
17.  		if (!in_array($key,array('NAME','POPESTIMATE2013','POPEST18PLUS2013'))) { unset($data[$i][$key]); }
18.  	}
19.  }
20.  
21.  //set options for your CSV generation
22.  $args = array(
23.    'download'=>false,
24.    'line_breaks'=>'unix',
25.    'trim'=>true
26.  );
27.  
28.  //generate the csv and print it out to the screen
29.  echo array_to_csv($data,$args);
30.  
31.  ?>

Here's the CSV:

1.   "NAME","POPESTIMATE2013","POPEST18PLUS2013"
2.   "Alabama","4833722","3722241"
3.   "Alaska","735132","547000"
4.   "Arizona","6626624","5009810"
5.   "Arkansas","2959373","2249507"
6.   "California","38332521","29157644"
7.   "Colorado","5268367","4030435"
8.   "Connecticut","3596080","2810514"
9.   "Delaware","925749","722191"
10.  "Florida","19552860","15526186"
11.  "Georgia","9992167","7502458"
12.  "Hawaii","1404054","1096788"
13.  "Idaho","1612136","1184355"
14.  "Illinois","12882135","9858828"
15.  "Indiana","6570902","4984875"
16.  "Iowa","3090416","2366384"
17.  "Kansas","2893957","2169865"
18.  "Kentucky","4395295","3381291"
19.  "Louisiana","4625470","3512513"
20.  "Maine","1328302","1067026"
21.  "Maryland","5928814","4584292"
22.  "Massachusetts","6692824","5298878"
23.  "Michigan","9895622","7650421"
24.  "Minnesota","5420380","4141269"
25.  "Mississippi","2991207","2253775"
26.  "Missouri","6044171","4646486"
27.  "Montana","1015165","791184"
28.  "Nebraska","1868516","1404168"
29.  "Nevada","2790136","2128531"
30.  "New Hampshire","1323459","1052337"
31.  "New Jersey","8899339","6877222"
32.  "New Mexico","2085287","1577747"
33.  "New York","19651127","15411151"
34.  "North Carolina","9848060","7562455"
35.  "North Dakota","723393","560705"
36.  "Ohio","11570808","8920978"
37.  "Oklahoma","3850568","2903541"
38.  "Oregon","3930065","3072459"
39.  "Pennsylvania","12773801","10058156"
40.  "Rhode Island","1051511","837524"
41.  "South Carolina","4774839","3695041"
42.  "South Dakota","844877","636918"
43.  "Tennessee","6495978","5004401"
44.  "Texas","26448193","19406207"
45.  "Utah","2900872","2004283"
46.  "Vermont","626630","503929"
47.  "Virginia","8260405","6395870"
48.  "Washington","6971406","5375611"
49.  "West Virginia","1854304","1472626"
50.  "Wisconsin","5742713","4434937"
51.  "Wyoming","582658","444979"
52.  "","",""

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.


Comments

Loading…

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.