Forum Moderators: coopster

Message Too Old, No Replies

Problem outputting column headings to CSV

         

galahad2

11:49 am on Feb 22, 2016 (gmt 0)

10+ Year Member



Hello, I've set up a CSV export script which works fine except that it doesn't output the actual field names as column headings in the resulting CSV. I've seen a lot of posts elsewhere about this kind of problem but unfortunately none of them worked with my exact script. Just wondered if anyone had any ideas? Interestingly the CSV's first row of cells is blank, so I'm wondering if it's trying to pull in the column headings but they're showing as blank?

[PHP]
if($_POST['export'])
{
$result = $mysqli->query('SELECT * FROM candidates WHERE IsArchived NOT LIKE "Y" ORDER BY CandidateName DESC');
if (!$result) { die('Couldn\'t fetch records'); }
$num_fields = $result->num_fields;
$headers = array();

for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysqli_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
ob_end_clean();
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 = mysqli_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
[/PHP]

galahad2

12:12 pm on Feb 22, 2016 (gmt 0)

10+ Year Member



Fixed now- amended loop. Thx,