所以这是我目前用于将特定表导出为.csv格式的代码。它到目前为止工作得很好,因为它下载文件并根据我的需要格式化数据。但是它不显示列名称
ex:目前显示
1 Jones Matt
2史密斯约翰3 Doe Jane
我希望它显示:
ID Last_Name First_Name
1 Jones Matt
2史密斯约翰3 Doe Jane
<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=applications.csv");
header("Pragma: no-cache");
header("Expires: 0");
ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$query = "SELECT * FROM applications";
$select_c = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
$result.="{$row['ID']},";
$result.="{$row['LAST_NAME']},";
$result.="{$row['FIRST_NAME']},";
$result.="{$row['ORGANIZATION']},";
$result.="{$row['TITLE']},";
$result.="\n";
}
echo $result;
?>
答案 0 :(得分:2)
这是添加列名称的快速而又脏的方法:
<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=applications.csv");
header("Pragma: no-cache");
header("Expires: 0");
ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$query = "SELECT * FROM applications";
$select_c = mysql_query($query) or die(mysql_error());
// -------------------- add the line below -----------------------------------
$result="ID,LAST_NAME,FIRST_NAME,ORGANIZATION,TITLE\n";
// -------------------- add the line above -----------------------------------
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
$result.="{$row['ID']},";
$result.="{$row['LAST_NAME']},";
$result.="{$row['FIRST_NAME']},";
$result.="{$row['ORGANIZATION']},";
$result.="{$row['TITLE']},";
$result.="\n";
}
echo $result;
?>
答案 1 :(得分:0)
只需在while
周期之前添加标题行:
echo "ID,Last_Name,First_Name,ORGANIZATION,TITLE\n";
答案 2 :(得分:0)
我假设你也想查询列名。
使用SELECT语句,您将永远不会在结果中获得列名。
在MySQL中你可以使用
SHOW COLUMNS FROM applications FROM db;
获取结果中的列名。
答案 3 :(得分:0)
此替代实现允许您使用fputcsv来防止数据中的逗号。
<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=applications.csv");
header("Pragma: no-cache");
header("Expires: 0");
ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$query = "SELECT ID, LAST_NAME, FIRST_NAME, ORGANIZATION, TITLE FROM applications";
$select_c = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($select_c, MYSQL_ASSOC);
$fp = fopen("php://output", "w");
fputcsv($fp, array_keys($row));
do {
fputcsv($fp, $rows);
} while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC));
?>