Php create csv file with header

I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.

I have the e-mailing of the link, MySQL query, etc. covered.

How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL?

I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.

d-_-b

20.4k39 gold badges139 silver badges233 bronze badges

asked Oct 20, 2008 at 3:11

header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");

function outputCSV($data) {
  $output = fopen("php://output", "wb");
  foreach ($data as $row)
    fputcsv($output, $row); // here you can change delimiter/enclosure
  fclose($output);
}

outputCSV(array(
  array("name 1", "age 1", "city 1"),
  array("name 2", "age 2", "city 2"),
  array("name 3", "age 3", "city 3")
));

php://output
fputcsv

Php create csv file with header

ntzm

4,6032 gold badges30 silver badges35 bronze badges

answered Jun 27, 2011 at 13:43

10

Try:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo "record1,record2,record3\n";
die;

etc

Edit: Here's a snippet of code I use to optionally encode CSV fields:

function maybeEncodeCSVField($string) {
    if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
        $string = '"' . str_replace('"', '""', $string) . '"';
    }
    return $string;
}

Popnoodles

28.6k2 gold badges44 silver badges53 bronze badges

answered Oct 20, 2008 at 3:15

Oleg BarshayOleg Barshay

3,7983 gold badges20 silver badges20 bronze badges

4

Here is an improved version of the function from php.net that @Andrew posted.

function download_csv_results($results, $name = NULL)
{
    if( ! $name)
    {
        $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
    }

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='. $name);
    header('Pragma: no-cache');
    header("Expires: 0");

    $outstream = fopen("php://output", "wb");

    foreach($results as $result)
    {
        fputcsv($outstream, $result);
    }

    fclose($outstream);
}

It is really easy to use and works great with MySQL(i)/PDO result sets.

download_csv_results($results, 'your_name_here.csv');

Remember to exit() after calling this if you are done with the page.

Php create csv file with header

ntzm

4,6032 gold badges30 silver badges35 bronze badges

answered Feb 14, 2012 at 19:07

XeoncrossXeoncross

54k77 gold badges255 silver badges361 bronze badges

6

In addition to all already said, you might need to add:

header("Content-Transfer-Encoding: UTF-8");

It's very useful when handling files with multiple languages in them, like people's names, or cities.

answered Mar 14, 2013 at 23:32

StanStan

1,2511 gold badge15 silver badges24 bronze badges

The thread is a little old, I know, but for future reference and for noobs as myself:

Everyone else here explain how to create the CSV, but miss a basic part of the question: how to link. In order to link to download of the CSV-file, you just link to the .php-file, which in turn responds as being a .csv-file. The PHP headers do that. This enables cool stuff, like adding variables to the querystring and customize the output:

Get CSV

my_csv_creator.php can work with the variables given in the querystring and for example use different or customized database queries, change the columns of the CSV, personalize the filename and so on, e.g.:

User_John_Doe_10_Dec_11.csv

answered Dec 10, 2011 at 9:07

LBJLBJ

1011 silver badge3 bronze badges

3

Create your file then return a reference to it with the correct header to trigger the Save As - edit the following as needed. Put your CSV data into $csvdata.

$fname = 'myCSV.csv';
$fp = fopen($fname,'wb');
fwrite($fp,$csvdata);
fclose($fp);

header('Content-type: application/csv');
header("Content-Disposition: inline; filename=".$fname);
readfile($fname);

Php create csv file with header

ntzm

4,6032 gold badges30 silver badges35 bronze badges

answered Oct 20, 2008 at 3:16

typemismatchtypemismatch

2,0272 gold badges23 silver badges25 bronze badges

1

Here is a full working example using PDO and including column headers:

$query = $pdo->prepare('SELECT * FROM test WHERE id=?');
$query->execute(array($id));    
$results = $query->fetchAll(PDO::FETCH_ASSOC);
download_csv_results($results, 'test.csv'); 
exit();


function download_csv_results($results, $name)
{            
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='. $name);
    header('Pragma: no-cache');
    header("Expires: 0");

    $outstream = fopen("php://output", "wb");    
    fputcsv($outstream, array_keys($results[0]));

    foreach($results as $result)
    {
        fputcsv($outstream, $result);
    }

    fclose($outstream);
}

Php create csv file with header

ntzm

4,6032 gold badges30 silver badges35 bronze badges

answered Jul 1, 2013 at 18:05

JustinJustin

25.2k16 gold badges108 silver badges126 bronze badges

First make data as a String with comma as the delimiter (separated with ","). Something like this

$CSV_string="No,Date,Email,Sender Name,Sender Email \n"; //making string, So "\n" is used for newLine

$rand = rand(1,50); //Make a random int number between 1 to 50.
$file ="export/export".$rand.".csv"; //For avoiding cache in the client and on the server 
                                     //side it is recommended that the file name be different.

file_put_contents($file,$CSV_string);

/* Or try this code if $CSV_string is an array
    fh =fopen($file, 'w');
    fputcsv($fh , $CSV_string , ","  , "\n" ); // "," is delimiter // "\n" is new line.
    fclose($fh);
*/

Hey It works very well....!!!! Thanks Peter Mortensen and Connor Burton

='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

?>

answered Feb 14, 2013 at 13:41

KaddyKaddy

311 bronze badge

1

You can simply write your data into CSV using fputcsv function. let us have a look at the example below. Write the list array to CSV file

$list[] = array("Cars", "Planes", "Ships");
$list[] = array("Car's2", "Planes2", "Ships2");
//define headers for CSV 
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file_name.csv');
//write data into CSV
$fp = fopen('php://output', 'wb');
//convert data to UTF-8 
fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($list as $line) {
    fputcsv($fp, $line);
}
fclose($fp);

Php create csv file with header

ntzm

4,6032 gold badges30 silver badges35 bronze badges

answered Mar 6, 2015 at 7:53

Php create csv file with header

ShahbazShahbaz

3,3431 gold badge25 silver badges42 bronze badges

Simple method -

$data = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"');

$fp = fopen('data.csv', 'wb');
foreach($data as $line){
    $val = explode(",",$line);
    fputcsv($fp, $val);
}
fclose($fp);

So each line of the $data array will go to a new line of your newly created CSV file. It only works only for PHP 5 and later.

Php create csv file with header

ntzm

4,6032 gold badges30 silver badges35 bronze badges

answered Feb 12, 2010 at 9:39

To have it send it as a CSV and have it give the file name, use header():

http://us2.php.net/header

header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');

As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.

answered Oct 20, 2008 at 3:15

Gavin M. RoyGavin M. Roy

4,3614 gold badges35 silver badges29 bronze badges

The easiest way is to use a dedicated CSV class like this:

$csv = new csv();
$csv->load_data(array(
    array('name'=>'John', 'age'=>35),
    array('name'=>'Adrian', 'age'=>23), 
    array('name'=>'William', 'age'=>57) 
));
$csv->send_file('age.csv'); 

answered Jul 25, 2011 at 18:51

Instead of:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

Use:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    echo implode(",", $row)."\n";
}

Php create csv file with header

answered Oct 29, 2010 at 15:29

Already very good solution came. I'm just puting the total code so that a newbie get total help

 $value) {
            //there may be separator (here I have used comma) inside data. So need to put double quote around such data.
        if(strpos($value, ',') !== false || strpos($value, '"') !== false || strpos($value, "\n") !== false) {
            $row[$key] = '"' . str_replace('"', '""', $value) . '"';
        }
    }
    echo implode(",", $row)."\n";
}

?>

I have saved this code in csv-download.php

Now see how I have used this data to download csv file

Php create csv file with header

So when I have clicked the link it download the file without taking me to csv-download.php page on browser.

answered Dec 17, 2012 at 16:19

zahid9izahid9i

5761 gold badge8 silver badges16 bronze badges

Writing your own CSV code is probably a waste of your time, just use a package such as league/csv - it deals with all the difficult stuff for you, the documentation is good and it's very stable / reliable:

http://csv.thephpleague.com/

You'll need to be using composer. If you don't know what composer is I highly recommend you have a look: https://getcomposer.org/

answered Jun 6, 2017 at 8:15

John HuntJohn Hunt

4,1088 gold badges42 silver badges59 bronze badges


How to write in CSV file using PHP script? Actually I was also searching for that too. It is kind of easy task with PHP. fputs(handler, content) - this function works efficiently for me. First you need to open the file in which you need to write content using fopen($CSVFileName, ‘wb’).

$CSVFileName = “test.csv”;
$fp = fopen($CSVFileName, ‘wb’);

//Multiple iterations to append the data using function fputs()
foreach ($csv_post as $temp)
{
    $line = “”;
    $line .= “Content 1″ . $comma . “$temp” . $comma . “Content 2″ . $comma . “16/10/2012″.$comma;
    $line .= “\n”;
    fputs($fp, $line);
}

Php create csv file with header

ntzm

4,6032 gold badges30 silver badges35 bronze badges

answered Oct 22, 2012 at 2:40

2

public function actionExportnotificationresponselogdata() {

    $fileName = '/tmp/notificationresponselogs_' . date('d-m-Y-g-i-h') . '.csv';
    $f = fopen($fileName, 'w'); 
     fputs( $f, "\xEF\xBB\xBF" ); //for utf8 support in csv



        $csv_fields=array();
        $csv_fields[] = 'heading1';
        $csv_fields[] = 'heading2';
        $csv_fields[] = 'heading3';
        $csv_fields[] = 'heading4';
        $csv_fields[] = 'heading5';
        $csv_fields[] = 'heading6';
        $csv_fields[] = 'heading7';
        $csv_fields[] = 'heading8';
        fputcsv($f, $csv_fields);

    
$notification_log_arr = $notificationObj->getNotificationResponseForExport($params); //result from database

    if (count($notification_log_arr) > 0) {
        $serialNumber=1;
    foreach ($notification_log_arr AS $notifaction) {
            

            $fields = array();
            $fields['serialNumber']= $serialNumber  ;
            $fields['fld_1']= $notifaction['fld_1'] ;
            $fields['fld_2']= $notifaction['fld_2'] ;
            $fields['fld_3']= $notifaction['fld_3'] ;
            $fields['fld_4']= $notifaction['fld_4'] ;
            $fields['fld_5']= $notifaction['fld_5'] ;
            $fields['fld_6']= $notifaction['fld_6'] ; 
            $fields['fld_7']= $notifaction['fld_7'] ; 
           // print_r($fields); die;
            fputcsv($f, $fields,",");
        
            $serialNumber++;  }
            fclose($f);
            if (file_exists($fileName)) {
                
                header("Content-type: application/csv");
                header("Content-Disposition: attachment; filename="."exportlog".date("Y-m-d_H:i").".csv");
                header("Content-length: " . filesize($fileName));
                header("Pragma: no-cache"); 
                header("Expires: 0");
                readfile($fileName);
                unlink($fileName);
                exit;
            }
}

answered Mar 4 at 5:58

Put in the $output variable the CSV data and echo with the correct headers

header("Content-type: application/download\r\n");
header("Content-disposition: filename=filename.csv\r\n\r\n");
header("Content-Transfer-Encoding: ASCII\r\n");
header("Content-length: ".strlen($output)."\r\n");
echo $output;

Php create csv file with header

David G

92k40 gold badges162 silver badges249 bronze badges

answered Nov 18, 2010 at 10:57