列名从mysql到csv

时间:2013-08-30 10:14:08

标签: php mysql csv

嘿,任何人都可以帮助我。我正在从mysql表创建一个csv用于客户端下载。数据插入并格式化为csv文件,但没有列名?任何帮助将非常感激。我是新手,所以请不要太多嘲笑:)

$result = mysqli_query($con,'SELECT * FROM score15ans WHERE id_user = "'.$userID.'" ORDER BY pps');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysqli_fetch_field($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 = $result->fetch_array(MYSQLI_NUM)) {
    fputcsv($fp, array_values($row));
}
die;
}

1 个答案:

答案 0 :(得分:0)

尝试

for ($i = 0; $i < $num_fields; $i++) {
    $headers[$i] = mysqli_fetch_assoc($result, $i);
    $headersField[$i] = $headers[$i]['Field'];
}

fputcsv($fp, $headersField);