使用PDO查询生成CSV下载 [英] Generating a CSV download using PDO queries
本文介绍了使用PDO查询生成CSV下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用户能够在我的服务器上下载所有数据的CSV备份. 这意味着我正在尝试执行多个查询,并将结果放入CSV文件中.
I am trying to make a user able to download a CSV backup of all of their data on my server. This means i am trying to execute multiple query's and placing the results into a CSV file.
这是我到目前为止所拥有的:
This is what i have so far:
<?php
// Connect
include 'config.php'; // Config contains PDO database connection, etc.
// Generate filename
$filename = $_SESSION['current_group'].'-'.date('d.m.Y').'.csv';
// Get backup data from MYSQL database
$result_users = $conn->prepare('SELECT `user_name`, `user_email` FROM `users` WHERE `group_id` = ?');
$result_users->execute(array($_SESSION['current_group_id']));
$result_items = $conn->prepare('SELECT `item_name`, `item_value`, `item_group` FROM `items` WHERE `group_id` = ?');
$result_items->execute(array($_SESSION['current_group_id']));
# Create array
$list = array ("## START OF USER TABLE ##");
// Append results to array
while ($row = $result_users->fetch(PDO::FETCH_ASSOC)) {
array_push($list, array_values($row));
}
array_push($list,"## END OF USER TABLE ##");
array_push($list,"## START OF ITEMS TABLE ##");
while ($row = $result_items->fetch(PDO::FETCH_ASSOC)) {
array_push($list, array_values($row));
}
array_push($list,"## END OF ITEMS TABLE ##");
// Output array into CSV file
$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
foreach ($list as $ferow) {
fputcsv($fp, split(',',$ferow));
}
?>
预期的输出应该是这样的:
The expected output is supposed to be something like:
## START OF USERS TABLE ##
"John","john@email.com"
"James","james@email.com"
## END OF USERS TABLE ##
## START OF ITEMS TABLE ##
"Soap","A lot","Household"
"Banana","2","Food"
## END OF ITEMS TABLE ##
等
问题是被赋值的值不能正确地推送到$ list数组中. 我该怎么做才能获得想要的结果?
The problem is that the valued do not correctly get pushed into the $list array. What should i do in order to get the wanted result?
谢谢!
推荐答案
我通过以下操作解决了该问题:
I solved it by doing the following:
// Create array
$list = array ();
// Append results to array
array_push($list, array("## START OF USER TABLE ##"));
while ($row = $result_users->fetch(PDO::FETCH_ASSOC)) {
array_push($list, array_values($row));
}
array_push($list, array("## END OF USER TABLE ##"));
// Output array into CSV file
$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
foreach ($list as $ferow) {
fputcsv($fp, $ferow);
}
这篇关于使用PDO查询生成CSV下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文