我正在尝试将表从 mysql 数据库导出到 csv。我能够成功地做到这一点,但是,它不会导出列名,有什么办法可以实现这一点吗?一些指针会很棒。请检查下面是我的 data_export.php 文件:
<?php
include 'class.user.php';
$conn=mysqli_connect("localhost","root","PASSWORD","reflective");
#declare the school variable for use in the select* query
$school = $_POST['school'];
#query the students table for data to export
$select="SELECT * FROM students WHERE school_id ='$school'";
$result = mysqli_query($conn, $select);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_num_fields($result);
$headers ="";
while ($property = mysqli_fetch_field($result)) {
$headers.= $property->name.",";
}
$headers.="\n";
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="students_data.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
?>
最佳答案
我建议您使用 PHP 中的 array_keys()
方法。它将从您从数据库获取的数组中提取所有键。您只需在方法中传递第一个数组作为参数,如下所示,
array_keys($data[0]);
关于php - 使用 PHP 从 mysql 导出到 csv 时获取列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54193166/