I have a script that turns a database query result into a csv file. The csv file's first row needs to be the field names of what's defined in the query. Here's what I have so far:
$fp = fopen('report.csv', 'w');
$column_names = array();
foreach($dbh->query($base_query, PDO::FETCH_ASSOC) as $row) {
if (empty($column_names)) {
$column_names = array_keys($row);
fputcsv($fp, $column_names);
}
// additional processing omitted ...
fputcsv($fp, $row);
}
fclose($fp);
Is there a nicer way to populate the column names in the first row of csv (do away with the if condition)? Perhaps do it outside of the loop? or have PDO output the column names before fetching data? Thanks.