【发布时间】:2013-06-02 07:21:45
【问题描述】:
我需要创建一个 CSV 文件来从 mySQL 数据库中获取数据。
事实是我希望 CSV tp 被更正标记,而不仅仅是像这样写数据:
id,name,url
1,thisismyname,thisismyurl
我需要 CSV 文件看起来井井有条,并且每个数据都插入到相关列中。
此外,使用我将在下面添加的功能,我只能从数据库中获取数据并将其按原样写入 CSV 文件。但我需要处理数据并以这种方式标记 CSV:
Campaign Name:
Name of the campaign
Campaign Url:
Url of the campaign
Tot visits:
Tot of visits
Tot unique visits:
Tot of unique visits
id name url
1 thisname this url
2 thisname this url
3 thisname this url
4 thisname this url
5 thisname this url
这是我到目前为止的 PHP 代码..我需要了解如何使用 PHP 实现正确的 CSV 结构,并以我想要的确切方式在其中添加行..
感谢您的帮助!
function genCSV($filename, $attachment = true, $headers = true) {
// send response headers to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=' . $filename);
$fp = fopen('php://output', 'w');
$query = "SELECT * FROM campaigns";
$result = mysql_query($query) or die(mysql_error());
if ($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result);
if ($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result, 0);
}
}
while ($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
}
【问题讨论】:
-
尝试让 mysql 为您完成工作:
SELECT ... INTO OUTFILE ...,将结果保存在您的应用程序可以访问的位置,看看这里:stackoverflow.com/questions/1119312/… -
您的问题在很大程度上取决于您的数据库的结构。表
campaigns有哪些列?是否需要其他表来收集您想要输出的所需信息?