2016-03-23 20 views
0

我有這段PHP代碼旨在從mySQL數據庫檢索數據,並將其導出到CSV文件,該文件必須在創建後自動下載。fputcsv創建文件,但將其下載爲空

$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection)); 

// fetch mysql table rows 
$sql = "select * from users"; 
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection)); 

$fp = fopen('users.csv', 'w'); 

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

fclose($fp); 

header('Content-Type: text/csv'); 

header('Content-Disposition: attachment; filename="users.csv"'); 

mysqli_close($connection); 

這裏的問題是,它:

  • 檢索數據。
  • 檢索服務器上的export.php文件的同一目錄中的CSV文件及其上的數據
  • 下載要與同名文件,但它是空的

感謝。

+1

你從來不屑輸出文件。你需要像'readfile('users.csv')'這樣的文件來讀取脫離磁盤的文件並將其吐出到客戶端。 –

+0

您不輸出僅發送文件名稱的文件內容,並且它是CSV。 – chris85

+0

而不是將其寫入服務器上的物理文件(如果您有併發用戶,則存在問題)使用''php:// output''作爲文件名(並在打開文件之前發送您的頭文件),該文件將直接發送給瀏覽器根本沒有使用任何服務器磁盤 –

回答

0

您正在將其寫入名爲users.csv的文件,但是您強制用戶下載的文件是頁面的輸出。

只要您的查詢是正確的,一旦PHP腳本運行,應該有一個名爲users.csv的文件與包含正確數據的PHP文件位於同一目錄中。

您需要將數據輸出到瀏覽器,以便將其歸因於您下載的文件。

試試這個:

//Connect to database 
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection)); 

//Fetch mysql table rows 
$sql = "select * from users"; 
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection)); 

//Close connection 
mysqli_close($connection); 

//Set $output 
$output = ""; 

//Set header values 
$headers = array("Header 1", "Header 2", "Header 3"); 

//Insert header values to $output 
foreach($headers as $h){ 
    $output .= fieldCheck($h) . ","; 
} 
$output = rtrim($output, ","). "\n"; 

//Iterate through results 
while($row = mysqli_fetch_assoc($result)) { 
    foreach($row as $cell){ 
     //Comma-separate each value 
     $output .= fieldCheck($cell).","; 
    } 
    //Remove last comma of each line and add newline 
    $output = rtrim($output, ",") . "\n"; 
} 

//Set headers 
header('Content-Type: text/csv'); 
header('Content-Disposition: attachment; filename="users.csv"'); 

//Output 
echo $output; 

exit; 

//Function in case of comma in field 
function fieldCheck($string){ 
    if(strpos($string, ",") !== false){ 
     $string = '"'.$string.'"'; 
    } 
    return $string; 
} 
+0

這工作完美除了分隔符,有沒有辦法使用「;」而不是「,」 ,有沒有辦法爲colums添加自定義標題?就像我在$ output =「」後面添加列名一樣; excel告訴我文件格式與擴展名不同,但它仍然可以打開。 –

+0

那麼,CSV代表「逗號分隔值」,所以通過使用分號';'或製表符,您可以使其無法通過CSV打開。你可以做的是創建一個函數,如果在字段中有一個逗號,將該字段用引號引起來 - 我已經將它添加到了我的答案中。我還添加了標題字段給我的答案。 – Ben

+0

它總是說這個類型與擴展指定的不同。它也表示它是SYLK格式,但它可能有錯誤(我的MS EXCEL是法文版) –