在 CSV 导出中输出列标题

Outputting Column titles in CSV Export

我有这个导出到 csv 文件的查询。它工作正常,我唯一想不通的是我还需要导出列标题,并将它们显示为全名、用户名、标志和原因。下面是代码,它可以很好地导出所有行,但我不确定如何导出相关行上方的列标题。

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=blackflag_bidders.csv");
header("Pragma: no-cache");
header("Expires: 0");




//SQL Query for Data
$sql = "SELECT ui.first_name, ui.last_name, u.username,
    if(u.flag=1,'BLK', if(u.flag=2,'NAA','')) flag,
    if(u.flag!=0, IFNULL(ui.note,''),'') reason
FROM user u
LEFT JOIN user_info ui ON ui.user_id=u.id
WHERE u.flag!=0;";

//Prepare Query, Bind Parameters, Excute Query
$STH = $sam_db->prepare($sql);
$STH->execute();



//Export to .CSV
$fp = fopen('php://output', 'w');
//fputcsv($fp);
while ($row = $STH->fetch(PDO::FETCH_NUM)) fputcsv($fp,$row);
fclose($fp);

您只需在页面中使用 HTML 的 <table> 标签以表格形式显示您的结果,即可获得 CSV 格式的列。

$result = "<table>";
    while ($row = $STH->fetch(PDO::FETCH_NUM)){
    $result .= "<tr><td>$row1</td><td>$row2</td><td>$row3</td></tr>";
}
$result .= "</table>";
fputcsv($fp, $result);

$row1, $row2 是指您在结果集中获得的值

一种方法是通过关联获取第一个结果,这些关联索引无论如何都是列。应用 array_keys 获取这些,然后首先添加 headers,然后添加第一个获取的行,然后循环其余行。

// first set
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
// $headers = array_map('ucfirst', $headers); // optional, capitalize first letter of headers
fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row

while ($row = $STH->fetch(PDO::FETCH_NUM))  {
    fputcsv($fp,$row); // push the rest
}
fclose($fp);

这个问题的答案取决于您是否已经知道列名。好像你在打电话(例如你已经在打电话 'Select ui.firstname...')

如果你不这样做,你可以通过查看这个线程来获取名称: What is the Select statement to return the column names in a table

一旦你有了名字,你只需要用这些名字创建一行并通过修改你的代码将它们添加到文件中:

//Export to .CSV
$columnNamesRow = "FirstName, LastName, UserName";
$fp = fopen('php://output', 'w');
fputcsv($fp, $columnNamesRow);

//fputcsv($fp);
while ($row = $STH->fetch(PDO::FETCH_NUM)) fputcsv($fp,$row);
fclose($fp);