gpt4 book ai didi

php - 创建 csv 文件时添加标题 PhP、SQL

转载 作者:行者123 更新时间:2023-11-29 07:06:05 26 4
gpt4 key购买 nike

我有以下代码:

哲学博士

function write_csv($filename, $rows) {
$file = fopen($filename, 'w');
while($row = mysqli_fetch_assoc($rows)) :
fputcsv($file, $row);
endwhile;

fclose($file);
}

// $db is a class I have and this function just returns a SQL result set
$result_set = $db->run_query("SELECT * FROM Users");

write_csv('../MOCK_USERS_DATA.csv', $result_set);

我正确地获取了一个创建的 CSV 文件,其中包含用户信息,例如

1,greg,mason,407-356-3322,greg@gmail.com
2,derek,herd,407-234-4352,derek@gmail.com

等...

我的问题是如何从表格中获取标题作为 CSV 文件的第一行。我是创建 CSV 文件的新手,并且一直致力于获取该文件中与数据库中的列名称相匹配的第一行标题。有什么建议吗?

最佳答案

轻松导出为 CSV

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

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

// output the column headings -> trim is used for lang translates
// or use SQL query to get table columns headers name
fputcsv($output, array(
trim('Product name'),
trim('Pellet number'),
trim('Quantity'),
trim('Date')
), ";");
// use foreach
***********
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");

// disposition / encoding on response body
header('Content-Disposition: attachment; filename=pelletlist-' . time() . '.csv');
header("Content-Transfer-Encoding: binary");
header("Cache-control: private"); //use this to open files directly
header('Expires: 0');
header("Pragma: no-cache");
header("Connection: close");
fclose($output);
exit();

用于从数据库加载列名称:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

SHOW COLUMNS FROM my_table;

关于php - 创建 csv 文件时添加标题 PhP、SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41593873/

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