Create Stream of CSV in PHP
Php 31-Oct-2019

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.

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.

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
// Make sure nothing else is sent, our file is done