我有一个将表导出为CSV文件的函数,然后使用电子表格应用程序打开该文件。
有没有办法设置CSV的标题以适当地命名每一列。
例如:
我有一张包含名字,姓氏,电子邮件和评论的表格。
表格设置为:fname,lname,email,comments
因此表格导出为:
fname, lname, email, comments
john, doe, johndoe@email.com, I am John Doe this is my comment
我想将标题(fname,lname,email,comments)更改为更具可读性的内容,所以它会是这样的:
First Name, Last Name, Email, Comments
john, doe, johndoe@email.com, I am John Doe this is my comment
这是我的代码:
function exportNamesCommentsCSV($table,$filename = 'volunteer_2009_comments.csv') {
$csv_terminated = "\n";
$csv_separator = ",";
$csv_enclosed = '"';
$csv_escaped = "\\";
$sql_query = "select lname, fname, comments from volunteers_2009";
// Gets the data from the database
$result = mysql_query($sql_query);
$fields_cnt = mysql_num_fields($result);
$schema_insert = '';
for ($i = 0; $i < $fields_cnt; $i++) {
$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
$schema_insert .= $l;
$schema_insert .= $csv_separator;
} // end for
$out = trim(substr($schema_insert, 0, -1));
$out .= $csv_terminated;
// Format the data
while ($row = mysql_fetch_array($result)) {
$schema_insert = '';
for ($j = 0; $j < $fields_cnt; $j++) {
if ($row[$j] == '0' || $row[$j] != '') {
if ($csv_enclosed == '') {
$schema_insert .= $row[$j];
} else {
$schema_insert .= $csv_enclosed .
str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
}
} else {
$schema_insert .= '';
}
if ($j < $fields_cnt - 1) {
$schema_insert .= $csv_separator;
}
} // end for
$out .= $schema_insert;
$out .= $csv_terminated;
} // end while
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=$filename");
echo $out;
exit;
}
答案 0 :(得分:2)
CSV文件的标题只是第一行。所以你要改变这个块:
for ($i = 0; $i < $fields_cnt; $i++) {
$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
$schema_insert .= $l;
$schema_insert .= $csv_separator;
} // end for
$out = trim(substr($schema_insert, 0, -1));
$out .= $csv_terminated;
您可以将其更改为非常简单的内容:
$out .= "First Name, Last Name, Email, Comments\n";
除非我完全误解了你的问题。
编辑:您的示例代码显示了一个特定查询。如果需要为多个查询工作,则必须找到这些友好名称的来源。例如,您可以将名称作为参数或store them in the database传递。
答案 1 :(得分:2)
您可以根据需要更改查询以重命名字段名称。
$sql_query = "select lname, fname, comments from volunteers_2009";
变为
$sql_query = "select fname as 'First Name', lname as 'Last Name',"
. "Comments from volunteers_2009";