0

I'm trying to export my data into a csv file and let the user to download it. I'm using fputcsv() function, but in the file, the data are written in a single cell instead of adjacent cells. I don't know what is the problem. Please help me. here is my code

session_start();
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename=report_'.time().'.csv;');
$data = $_SESSION['data'];
$file = fopen('php://output','w');
foreach($data as $i=>$value)
{
    fputcsv($file, $value,";");
}
fclose($file);

and this is how the file looks like..

and this is how the file looks like..

Anand Solanki
  • 3,419
  • 4
  • 16
  • 27
Vignesh
  • 1,045
  • 2
  • 17
  • 34

2 Answers2

1

try like

 $data = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"');
$fp = fopen('php://output', 'w+'); 
header('Content-type: application/octet-stream');  
header('Content-disposition: attachment; filename="data.csv"'); 
foreach($data as $line){
    $val = explode(",",$line);
    fputcsv($fp, $val);
}
fclose($fp);

or try may be according your data

foreach($data as $i=>$value)
{
    fputcsv($file, $value);
}
Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44
1

Use , instead of ; for delimiter

Replace fputcsv($file, $value,";"); with fputcsv($file, $value, ","); and try

Example:

header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename=report_'.time().'.csv;');
$data = array(array('one' => 1, 'two' => 2));
$file = fopen('php://output','w');
foreach($data as $i => $value)
{
    //fputcsv($file, $value, ";");
    fputcsv($file, $value, ",");
}
fclose($file);
Manoj Yadav
  • 6,560
  • 1
  • 23
  • 21