December 23, 2023 5:03 am

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;
?>

 

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

3 responses to “Create Stream of CSV in PHP”

  1. Angel says:

    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)?

  2. Max John says:

    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 ?

Leave a Reply

Your email address will not be published. Required fields are marked *