gpt4 book ai didi

PHP:下载 MySQL 表

转载 作者:可可西里 更新时间:2023-11-01 08:26:22 24 4
gpt4 key购买 nike

我想将 MySQL 表下载为 CSV 文件,但出现此错误“允许的内存大小为 1342177280 字节已耗尽”。我想那是因为文件是先创建然后下载的。我怎样才能实现用户可以从 0 开始下载文件,在这种情况下我认为我不需要那么多内存。

到目前为止,这是我的代码:

$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;

最佳答案

所以最后这就是我想要的:

$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);

关于PHP:下载 MySQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35220812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com