EricC
EricC

Reputation: 1439

turning db data into csv with header row in php

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

Answers (2)

Your Common Sense
Your Common Sense

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

Jason McCreary
Jason McCreary

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

Related Questions