IMG-LOGO
Home Tutorial How to Export CSV in PHP

How to Export CSV in PHP

by MH RISHAD - 08 Sep 2019
IMG

Export CSV Using 

If you need to send a CSV file directly from the browser, without writing in an external file, you can open the output and use fputcsv on it..

$csv= fopen('php://output', 'w');
fputcsv($csv, array('column1','column2', 'column3','column4.'));
fclose($csv);

Utility function to output a mysql query to csv with the option to write to file or send back to the browser as a csv attachment.

  header( 'Content-Type: text/csv' );
  header( 'Content-Disposition: attachment;filename='.$filename);
  $fp = fopen('php://output', 'w');

Array Listing Create csv ::::


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

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp); 

The above example will write the following to file.csv:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

 Must use header Before Export CSV File

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

Full Example Code :::

 function createCsv(){
$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=your_desired_name.csv");
header("Pragma: no-cache"); header("Expires: 0")

$fp = fopen('textfile.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp); 
}
Tags:
Share:

Leave a Comment

Required fields are marked *