Create Stream of CSV in PHP
CSV Streaming is a method for users to export their data in excel, a way for user to backup hosted data or send report to users.
In this tutorial we have are working on how we can export data in CSV to your customers.
PHP Code
Start by sending the headers to allow the user to download the csv file Download.php
$fileName = 'myfile.csv'; header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header('Content-Description: File Transfer'); header("Content-type: text/csv"); header("Content-Disposition: attachment; filename={$fileName}"); header("Expires: 0"); header("Pragma: public"); $fh = @fopen( 'php://output', 'w' );
Database configuration file you have to modify username, password and database name values.
<?php define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'Username'); define('DB_PASSWORD', 'Password'); define('DB_DATABASE', 'Database'); $connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error()); $database = mysql_select_db(DB_DATABASE) or die(mysql_error()); ?>
Select Data from database to write in your csv file bellow code will write your csv file.
<?php include = "db.php"; $results = mysql_query("SELECT * FROM `my_table`"); $headerDisplayed = false; while ($data = mysql_fetch_array($results, MYSQL_NUM)) { // Add a header row if it hasn't been added yet if ( !$headerDisplayed ) { // Use the keys from $data as the titles fputcsv($fh, array_keys($data)); $headerDisplayed = true; } // Put the data into the stream fputcsv($fh, $data); } // Close the file fclose($fh); // Make sure nothing else is sent, our file is done exit; ?>
Tutorial Categories:
hi, i’m has been read your blog for the last year and really help me to much in my projects… I have a question. How can get in the header the name of columns of database table instead array_keys($data)?
Which one is db.php ? I can see include db.php but it seems you did not mention which file is that . Is that the file that enables to connect to mysql ?
yes database connection file.