PHP: Export Query Results to a CSV File

Printing out nicely formated tables in HTML is good, but the downside is that sorting and aggregation options can be sometimes limited. If you didn’t write the code for it, your users won’t be able to do it. This is why a lot of business people like Excel - it gives them the power to sort, aggregate and transform data without having to talk to the developers and wait till a given data filter or sorting feature is implemented, tested and rolled out into production. So I usually include simple export-to-excel option in a lot of the reports. Here is the little generic function I use to dump out the data in a comma separated values (CSV) format, and set the headers so that the browser prompts the user to save it or open it in Excel.

<?php
 
// takes a database resource returned by a query
function csv_from_mysql_resource($resource)
{
	$output = "";
	$headers_printed = false;
 
	while($row = mysql_fetch_array($resource, MYSQL_ASSOC))
	{
		// print out column names as the first row
		if(!$headers_printed)
		{
			$output .= join(',', array_keys($row)) ."\n";
			$headers_printed = true;
		}
 
		// remove newlines from all the fields and
		// surround them with quote marks
		foreach ($row as &$value)
		{
			$value = str_replace("\r\n", "", $value);
			$value = "\"" . $value . "\"";
		}
 
		$output .= join(',', $row)."\n";
 
	}
 
	// set the headers
	$size_in_bytes = strlen($output);
	header("Content-type: application/vnd.ms-excel");
	header("Content-disposition:  attachment; filename=export_data.csv; size=$size_in_bytes");
 
	// send output
	print $output;
	exit;
}
 
?>

Note that you will be sending headers to the browser, so you need to run this function before you print any HTML on the page. I’m removing newlines from all the text fields - since my table had 2 TEXT columns with free form textual data in them, the newlines were causing no end of havoc. Note that the & operator doesn’t work in PHP4 so you might need to do some old fashioned assignment.

Related Posts:

  • Dump MySQL table into CSV file
  • Convert a large Access table into Excel files
  • Lisp: Parse and Aggregate a CSV File
  • Samsung A670 - Sync with PC
  • In defense of office suite databases
  • Convert PS and EPS images to JPEG
  • DST Readines Test for MySQL and PHP
  • MINUS query in MySQL
  • Indexing Really Helps
  • AOL Search Query Fun

  • 12 Responses to “PHP: Export Query Results to a CSV File”

    1. Gravatar Anthony V UNITED STATES Says: Reply to this comment

      this is a livesaver! thank you!

      Whoa, so happy I didn’t have to code this! )

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.7 on Windows Windows XP
    2. Gravatar Luke Maciak UNITED STATES Says: Reply to this comment

      Awesome. I’m glad you found this useful. )

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.6 on Ubuntu Linux Ubuntu Linux
    3. Gravatar Barbara F UNITED STATES Says: Reply to this comment

      This is EXACTLY what I was looking for - and so simple to use.

      Thank you!!!!!

      Posted using Internet Explorer Internet Explorer 6.0 on Windows Windows 2000
    4. Gravatar Joe UNITED STATES Says: Reply to this comment

      Instead of removing the ‘/r/n’ you should consider replacing it with ‘’ to preserve the line break position without causing havoc in your CSV.

      You can always convert back from ‘’ to ‘\r\n’ if you need to later but you cannot add newlines back in if you removed them…

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.8 on Windows Windows XP
    5. Gravatar Joe UNITED STATES Says: Reply to this comment

      replace it with an HTML Line break:

      the ’s got eaten out of my last comment.

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.8 on Windows Windows XP
    6. Gravatar Joe UNITED STATES Says: Reply to this comment

      I meant: ‘’

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.8 on Windows Windows XP
    7. Gravatar Luke Maciak UNITED STATES Says: Reply to this comment

      Wordpress strips HTML tags by default. If you use the code button you can override that behavior. Either that, or use HTML entities &lt; and &gt; for < and >

      Thanks for the tip though )

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.6 on Ubuntu Linux Ubuntu Linux
    8. Gravatar Chris UNITED KINGDOM Says: Reply to this comment

      I’m a PHP newbie and don’t understand how you get this function to execute and pass it a query it’ll output in CSV format.

      I either get the error message “Parse error: parse error, unexpected ‘&’, expecting T_VARIABLE or ‘$’” in the line where “foreach ($row as &$value)
      ” appears - I’m running PHP5 - or else a blank white page. Any chance you can expand on implementing this function?

      Posted using Internet Explorer Internet Explorer 6.0 on Windows Windows XP
    9. Gravatar Luke Maciak UNITED STATES Says: Reply to this comment

      You want to run your query in the usual way and then you pass the result to the function:

      <?php
      // lets say my function is in a file cvs_export.php
      require("cvs_export.php")
       
      // connect to the db
      $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');
      mysql_select_db('my_database');
       
      // run the query
      $result = mysql_query("SELECT * FROM my_table");
       
      // pass the result to my function:
      csv_from_mysql_resource($result);
      ?>

      As for the error, it almost looks like something you would get with PHP4 which has no passing by reference. You can easily rewrite the foreach loop like this:

      foreach ($row as $key => $value)
      {
              $row[$key] = str_replace("\r\n", "", $value);
              $row[$key] = "\"" . $value . "\"";
      }

      This removes the pass by reference syntax that seems to be causing the error. Just make sure you don’t have any white spaces before or after the PHP tags and you should be fine. )

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.6 on Ubuntu Linux Ubuntu Linux
    10. Gravatar Chris UNITED KINGDOM Says: Reply to this comment

      Thanks Luke, that worked great and really helps with my learning. I will be sure to explore more of your PHP/MySQL posts.
      Chris

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.9 on Windows Windows Vista
    11. Gravatar Adam UNITED STATES Says: Reply to this comment

      Thanks for the great info! This really helped me a lot.

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.14 on Windows Windows XP
    12. Gravatar Dave UNITED STATES Says: Reply to this comment

      Thanks. I tried several scripts to do this but yours was simplest and most effective.

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.16 on Windows Windows XP

    Leave a Reply

    XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <pre lang=""> <em> <i> <strike> <strong>

    [Quote selected]