Advanced CSV Export
By: Daniel

In one of my last tutorials I explained how you can export data into a CSV. You can see that tutorial at: Export data to CSV (Comma Separated Value). In this tutorial you will learn more about getting items from a database instead of hand coding the CSV contents.

<?php
$db = mysql_connect('localhost', 'username', 'password'); // Connect to the database
$link = mysql_select_db('database name', $db); // Select the database name

function parseCSVComments($comments) {
  $comments = str_replace('"', '""', $comments); // First off escape all " and make them ""
  if(eregi(",", $comments) or eregi("\n", $comments)) { // Check if I have any commas or new lines
    return '"'.$comments.'"'; // If I have new lines or commas escape them
  } else {
    return $comments; // If no new lines or commas just return the value
  }
}

$sql = mysql_query("SELECT * FROM tableName"); // Start our query of the database
$numberFields = mysql_num_fields($sql); // Find out how many fields we are fetching

if($numberFields) { // Check if we need to output anything
	for($i=0; $i<$numberFields; $i++) {
		$head[] = mysql_field_name($sql, $i); // Create the headers for each column, this is the field name in the database
	}
	$headers = join(',', $head)."\n"; // Make our first row in the CSV

	while($info = mysql_fetch_object($sql)) {
		foreach($head as $fieldName) { // Loop through the array of headers as we fetch the data
			$row[] = parseCSVComments($info->$fieldName);
		} // End loop
		$data .= join(',', $row)."\n"; // Create a new row of data and append it to the last row
		$row = ''; // Clear the contents of the $row variable to start a new row
	}
	// Start our output of the CSV
	header("Content-type: application/x-msdownload");
	header("Content-Disposition: attachment; filename=log.csv");
	header("Pragma: no-cache");
	header("Expires: 0");
	echo $headers.$data;
} else {
	// Nothing needed to be output. Put an error message here or something.
	echo 'No data available for this CSV.';
}
?>

As you will see in this tutorial I have continued to use the parseCSVComments() function from the previous tutorial. This ensures that your data is going to come out how you want it to appear in the CSV.

The best part about this script is that any table you put in the query on line 14 will be the headers and data in the CSV. No need to hand type out all the table headers unless you want to comment that section out and put in your own. So if you have a table full of users that includes: name, email, website, phone you could create a query like:

SELECT name, email, website, phone FROM users

This would pull only those fields to the CSV if you had other data like passwords, nicknames or instant messenger addresses in the same table.

Enjoy!

4 Votes | Average: 4.25 out of 54 Votes | Average: 4.25 out of 54 Votes | Average: 4.25 out of 54 Votes | Average: 4.25 out of 54 Votes | Average: 4.25 out of 5 (4 votes, average: 4.25 out of 5)
Loading ... Loading ...
del.icio.us:Advanced CSV Export digg:Advanced CSV Export spurl:Advanced CSV Export wists:Advanced CSV Export simpy:Advanced CSV Export newsvine:Advanced CSV Export blinklist:Advanced CSV Export furl:Advanced CSV Export reddit:Advanced CSV Export fark:Advanced CSV Export blogmarks:Advanced CSV Export Y!:Advanced CSV Export smarking:Advanced CSV Export magnolia:Advanced CSV Export segnalo:Advanced CSV Export

6 Responses to “Advanced CSV Export”

  1. Kelly Says:

    COOL
    Been looking for this type of php Advanced CSV Export, but I need it to export to a table in a html page every time someone adds to database.
    If you have a sample of that it would be great.

  2. Derek Buntin Says:

    I would just like to say thanks for this, we used an INNER JOIN on two tables and it exported perfectly ;-)

  3. problem Says:

    i am using it it display data on browser not in neither create csv nor put data even i put log.csv in the same location.still not working can u explain me.

  4. Clive Says:

    Fantastic! Just what I was looking for. I’ve simply added in my own database specific info in the first couple of lines and it outputs everything exactly as I wanted. Many thanks!

  5. nichole Says:

    thanks this is what i was looking for. but i have one problem. i want to display the header in first two row in log.csv file. i can display the header in single cell but not in merge cell. if you have some idea then it would be great help.

  6. Lou Says:

    Very easy to use, thank you! Two questions. #1. How can I combine two db fields into one csv cell? ex. First_Name and Last_name in the same cell. #2. Is there a way to export by date range instead of the entire db? That way I can select only the past few days I haven’t downloaded instead of the entire db.

    Thanks again!

Leave a Reply

eXTReMe Tracker
geovisitors