Taylor Foster
Taylor Foster

Reputation: 1195

Adding the headers when creating a csv file PhP, SQL

I have the following code:

PhP

function write_csv($filename, $rows) {
  $file = fopen($filename, 'w');
  while($row = mysqli_fetch_assoc($rows)) :
    fputcsv($file, $row);
  endwhile;

  fclose($file);
 }

 // $db is a class I have and this function just returns a SQL result set
 $result_set = $db->run_query("SELECT * FROM Users");

 write_csv('../MOCK_USERS_DATA.csv', $result_set);

I am correctly getting a created CSV file with the the users information for example

1,greg,mason,407-356-3322,[email protected]
2,derek,herd,407-234-4352,[email protected]

etc...

My question is how do I get the headers from the table as the first row in my CSV file. I am new to creating CSV files and am stuck on getting that first row of headers in that file that match the name of the column in my database. Any suggestions?

Upvotes: 0

Views: 889

Answers (1)

Jan Sršeň
Jan Sršeň

Reputation: 1095

Easy export to CSV

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');

ob_start();
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings -> trim is used for lang translates
// or use SQL query to get table columns headers name
fputcsv($output, array(
    trim('Product name'),
    trim('Pellet number'),
    trim('Quantity'),
    trim('Date')
        ), ";");
// use foreach
***********
// force download  
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");

// disposition / encoding on response body
header('Content-Disposition: attachment; filename=pelletlist-' . time() . '.csv');
header("Content-Transfer-Encoding: binary");
header("Cache-control: private"); //use this to open files directly
header('Expires: 0');
header("Pragma: no-cache");
header("Connection: close");
fclose($output);
exit();

for load column name from db use:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

or

SHOW COLUMNS FROM my_table;

Upvotes: 1

Related Questions