0

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.

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.