2016-07-08 135 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