fputcsv - 函数给出错误。

时间:2014-04-29 11:47:42

标签: php fputcsv

我尝试将数据导出到csv文件中,然后让用户下载它。我使用fputcsv()函数,但在文件中,数据写入单个单元格而不是相邻单元格。我不知道是什么问题。请帮我。这是我的代码

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

2 个答案:

答案 0 :(得分:1)

尝试

 $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);

或尝试可能是根据您的数据

foreach($data as $i=>$value)
{
    fputcsv($file, $value);
}

答案 1 :(得分:1)

,

使用;代替delimiter

fputcsv($file, $value,";");替换为fputcsv($file, $value, ",");并尝试

示例:

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