2016-07-08 133 views
0

我试图用下面的代码将一些数据导出为csv,但它在文件末尾附加了一个不需要的'null'。fputcsv在文件末尾附加'null'

$array = array(); 
$fileName = 'test.csv'; 
$array[0] = ['Name','Email']; 
$array[1] = ['Test','[email protected]']; 
$fileObj = new FileStream(); 
$fileObj->array_to_csv_download($array,$fileName); 

array_to_csv_download码 -

$f = fopen('php://memory', 'w'); 
    foreach ($array as $line) { 
     $this -> logObj -> LogError(" CSV ".json_encode($line)); 
     fputcsv($f, $line, $delimiter); 
    } 
    fseek($f, 0); 
    header('Content-Type: application/csv'); 
    header('Content-Disposition: attachment; filename="'.$filename.'";'); 
    fpassthru($f); 

输出 -

Name,Email 
Test,[email protected] 
null 

我缺少的东西?

+0

什么是FileStream的array_to_csv_download()代码?和'test.csv'的内容是什么# –

+0

@MarcinOrlowski对不起,我错过了。请立即检查。 – Harshit

+0

显然你错过了迭代器(fpassthru或任何其他)在它们到达文件结尾(eof)时返回null的事实。在eof中没有“空字符”。这是您可以使用'while not null'语句来确定eof的方式。 –

回答

1

如何直接生成CSV?适用于我。

header('Content-Type: application/csv'); 
foreach($array as $fields) { 
    echo implode(",", $fields)."\n"; 
} 
+0

这也附加一个null。 – Harshit