I’m successfully creating a CSV file from a query and saving the file on the server, but I can not get the csv to contain the header fields, per the query column names. I am creating a headers array from the mysql_field_name, but can’t get it to write the headers to the csv, it only writes the table data. Any thoughts / examples greatly appreciated.
//Create a CSV for
$result = mysql_query("SELECT * FROM `car_details`");
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);
}
$csv_filename = "Policy-" .$datetime.".csv";
$fp = fopen($csv_filename, 'w+');
if ($fp && $result)
{
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
}
Try writing $headers to the file as the first line.