2016-02-05 21 views
3

我想下載一個MySQL表作爲CSV文件,但我得到這個錯誤「允許的內存大小1342177280字節用盡」。我想這是因爲該文件是第一次創建,然後下載。我怎樣才能確定用戶可以從0開始下載文件,在這種情況下,我認爲我不需要太多內存。PHP:下載MySQL表

這是我到目前爲止的代碼:

$output   = ""; 
$table   = "export_table"; 
$sql   = mysql_query("select * from $table"); 
$columns_total = mysql_num_fields($sql); 

// Get The Field Name 
for ($i = 0; $i < $columns_total; $i++) { 
    $heading = mysql_field_name($sql, $i); 
    $output  .= '"'.$heading.'",'; 
} 
$output .="\n"; 
// Get Records from the table 
while ($row = mysql_fetch_array($sql)) { 
for ($i = 0; $i < $columns_total; $i++) { 
$output .='"'.$row["$i"].'",'; 
} 
$output .="\n"; 
} 
// Download the file 
$filename = "export.csv"; 
header('Content-type: application/csv'); 
header('Content-Disposition: attachment; filename='.$filename); 
echo $output; 
+0

您的代碼的難看解決方案是ini_set('memory_limit', - 1);它不會給這個錯誤。 –

+1

在SO上搜索'MYSQL SELECT INTO OUTFILE'並給我一杯飲料,因爲使用它之後你真的會很開心,相比於你自己的方法:) –

+0

另一個解決方案是你在服務器上寫完整個文件並允許使用它。 –

回答

2

最後這是我想要做什麼:

$db = mysqli_connect("localhost", "user", "password", "database"); 

$result = mysqli_query($db, "SELECT * FROM export_table", MYSQLI_USE_RESULT); 

header("Content-Type: application/force-download"); 
header("Content-Type: application/octet-stream"); 
header("Content-Type: application/download"); 
header("Content-Disposition: attachment;filename=\"export_table.csv\""); 
header("Content-Transfer-Encoding: binary"); 
header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: private",false); 

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

    fputcsv($output, array('ID','Column1','Column2','Column3')); 

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

fclose($output); 
mysqli_free_result($result); 
mysqli_close($db); 
+0

另一個例子也可以做到這一點。 http://code.stephenmorley.org/php/creating-downloadable-csv-files/,需要解決這個問題的人。 –

0

你將不得不遍歷結果集,而不是分配給$輸出變量之前將你的頭功能,只不過是迴應它。

// ... 

$filename = "export.csv"; 
header('Content-type: application/csv'); 
header('Content-Disposition: attachment; filename='.$filename); 

// Just dump the records you fetch from the db into output 
while ($row = mysql_fetch_array($sql)) { 
    $line = ''; 
    for ($i = 0; $i < $columns_total; $i++) { 
     $line .= '"' . $row["$i"] . '",'; 
    } 
    echo $line, "\n"; 
} 

這可能有其存在的問題,根據您的具體情況,但應作爲一個快速和骯髒的解決方案工作。

0

使用此代碼: -

$dbhost = 'localhost'; 
$dbuser = 'root'; 
$dbpass = 'password'; 
$dbname = 'dbName'; 
$tableName = 'tableName'; 
$mysqldump=exec('which mysqldump'); 

$command = "$mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbname $tableName > $tableName.sql"; 

exec($command); 

如果您需要下載整個數據庫然後通過這條線替換$command: -

$command = "$mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbname > $dbName.sql"; 

希望這將有助於所以你:)