2013-06-18 42 views
2

我已經成功地將我的數據庫導出到csv作爲可下載的文件。然而,我現在需要做的是不是創建一個直接下載的.csv文件,而是將它保存到服務器上名爲「csv」的文件夾中。這是我當前導出的代碼。我需要幫助保存到服務器。我沒有正確保存數據。數據庫到CSV(完成)嘗試將文件保存到服務器上的文件夾

// output headers so that the file is downloaded rather than displayed 
header('Content-Type: text/csv; charset=utf-8'); 
header('Content-Disposition: attachment; filename=data.csv'); 

// create a file pointer connected to the output stream 
$output = fopen('php://output', 'w'); 

// output the column headings 
fputcsv($output, array('tax_class_id','_product_websites')); 

// fetch the data 
mysql_connect('localhost:3036', 'x', 'x'); 
mysql_select_db('lato'); 
$rows = mysql_query('SELECT taxclass,productwebsite FROM product'); 

// loop over the rows, outputting them 
while ($row = mysql_fetch_assoc($rows)) 
fputcsv($output, $row); 

$filename = "data.csv"; // Trying to save file in server 
file_put_contents("download/" . $filename, "$header\n$rows"); 

回答

1

爲什麼在流中寫入,讀取它並嘗試保存內容? 我會以更小的方式做到這一點:

//Open a file in write-mode (he creates it, if it not exists) 
$fp = fopen('./my/path/on/server/data.csv', 'w'); 

// output the column headings 
fputcsv($fp, array('tax_class_id','_product_websites')); 

// fetch the data 
mysql_connect('localhost:3036', 'x', 'x'); 
mysql_select_db('lato'); 
$rows = mysql_query('SELECT taxclass,productwebsite FROM product'); 

// loop over the rows, outputting them 
while ($row = mysql_fetch_assoc($rows)) 
fputcsv($fp, $row); 
//close the handler 
fclose($fp); 
相關問題