2016-11-25 12 views
0

我試圖使用php將我的sql查詢保存爲csv。一切順利,除了在csv文件的開頭有一個空行。我怎樣才能刪除開始的空白行?這裏是我的代碼:PHP - 將數組保存爲CSV時的空白行

include('connectdb.php'); 
mysqli_error($mysqli)); 


header('Content-type: text/csv'); 
header('Content-Disposition: attachment; filename="online_applicants.csv"'); 

header('Pragma: no-cache'); 
header('Expires: 0'); 

$file = fopen('php://output', 'w'); 

$sql = "select Firstname from applicant"; 
$result = mysqli_query($mysqli, $sql) or die("selection error " .  
mysqli_error($mysqli)); 

while($row = mysqli_fetch_assoc($result)) 
{ 
    fputcsv($file, $row); 
} 



fclose($file); 

謝謝!

+1

愚蠢的問題,但你確定數據庫中沒有任何空行嗎? –

+0

我相信沒有「愚蠢」的問題伴侶這樣的事情。 ;)我確定我的數據庫中沒有空行。空行總是出現在csv文件的第一行。 –

回答

0

之前保存該行,你可以嘗試檢查,如果該行是空白的,例如:

while($row = mysqli_fetch_assoc($result)) 
{ 
if ($row != "") { 
    fputcsv($file, $row); 
} 
} 

或者你也可以檢查大小,通常是「空白」行可能有一些,但規模會小於正常行,例如:

while($row = mysqli_fetch_assoc($result)) 
{ 
if (strlen($row) > 5) { // if the row has more than 5 characters, put in the file 
    fputcsv($file, $row); 
} 
} 
+0

我的數據庫中沒有空行,但是當我打開csv時,結果總是在開始處有一個空行。 –

+0

這是空白行,只是一個換行符(\ n)? – bruno

+0

但我的代碼的哪一部分放入了換行符?我試圖迴應結果,我沒有看到任何換行符。 –