Reputation: 1439
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.
Upvotes: 0
Views: 192
Reputation: 158009
There is always a nicer way, if you separate different operations from each other.
//database part
$data = $dbh->query($base_query)->fetchAll();
// header part
$fp = fopen('report.csv', 'w');
$column_names = array_keys($data[0]);
fputcsv($fp, $column_names);
// body part
foreach($data as $row) {
// additional processing omitted ...
fputcsv($fp, $row);
}
Upvotes: 1
Reputation: 73031
Is there a nicer way to populate the column names in the first row of csv (do away with the if condition)?
No.
Perhaps do it outside of the loop?
Your code is inferring the column names from the keys of the fetched row and as such needs to be inside the loop.
PDO output the column names before fetching data?
This would require an additional query or storing metadata otherwise. Both of which are extra work.
Upvotes: 0