Just another WordPress site
CSV (comma-separated values) is the most widely supported format for transferring tabular data between applications. The ability to export data in CSV format is a useful feature for many programs, and is becoming increasingly common in web applications. This page explains how to use PHP to create CSV files, and how to ensure that your visitor’s browser offers to download the file instead of displaying it.
The following code assumes that the data to be exported are stored in a MySQL database, but it can easily be modified to work with other data sources, and hence serves as a general template:
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
The string ‘data.csv’ on line 3 is the name the browser will suggest for the downloaded file. The array literal on line 9 contains the column headings; this line should be omitted altogether if you do not wish to include column headings. The strings on lines 12 to 14 should be changed to the appropriate connection parameters and query string for your database. In a real application the database connection parameters should be defined as constants in a separate configuration file.
I am an expert level developer focusing on both front and backend developing. Theres a huge number of languages I use to develop with the main being PHP, MySQL and jQuery. I also have experience in building with Oracle PLSQL via PHP creating more powerful applications and modules.
Working with a massive number of large companies I have been able to secure partnership in a company called ello-u.com a super social networking site which is about to hit the social world. features rich functionality to give the user a better more powerful experience and less clutter and hassle. Give that user the real social experience they were originally after.
Leave a reply
You must be logged in to post a comment.