This is something you’re likely to do several times in several different scenarios. The common one for me is generating reports from a database.
I tend to build a $_SESSION array as I run the SQL query that is displayed on the page, and then provide a link to ‘Download CSV’. Then the csv-export script just needs to output the array….
Here’s a great tutorial of how to Export your MySQL database to .csv file format and another Export MySQL data records to an Excel file….
…and another from the legendary Mark Jackson… http://www.mjdigital.co.uk/blog/export-mysql-table-to-excel/
Plus, this one I’ve used a few times, it’s on a Sitepoint forum
<? // Connect database $database="tutorial"; $table="name_list"; mysql_connect("localhost","",""); mysql_select_db("tutorial"); $result=mysql_query("select * from $table"); $out = ''; // Get all fields names in table "name_list" in database "tutorial". $fields = mysql_list_fields(tutorial,$table); // Count the table fields and put the value into $columns. $columns = mysql_num_fields($fields); // Put the name of all fields to $out. for ($i = 0; $i < $columns; $i++) { $l=mysql_field_name($fields, $i); $out .= '"'.$l.'",'; } $out .="n"; // Add all values in the table to $out. while ($l = mysql_fetch_array($result)) { for ($i = 0; $i < $columns; $i++) { $out .='"'.$l["$i"].'",'; } $out .="n"; } // Open file export.csv. $f = fopen ('export.csv','w'); // Put all values from $out to export.csv. fputs($f, $out); fclose($f); header('Content-type: application/csv'); header('Content-Disposition: attachment; filename="export.csv"'); readfile('export.csv'); ?>
Main Category
Secondary Categories