Search code examples
phpfputcsv

fputcsv - Function gives Error.


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..


Solution

  • 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);
    }