我正在使用 php 运行 SQL 查询并填充 HTML 表。我的问题是,由于我有 $query 变量存放 sql 结果,是否可以向“导出到 CSV”添加一个按钮,如果单击该按钮,它将导出格式化的 $query 的 .csv 文件和生成的html表一样吗?
假设查询字符串是这样的:
$query .= "Select red, green, blue from colorsDB where signoff is not null";
$db->setQuery($query);
$query = $db->loadObjectList();
你可以试试这个方法
$result = mysql_query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句