Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - writing column headers to CSV

Tags:

php

csv

I have an array called $contents which I loop through and write to CSV. I'd like to write column headers to the top of the CSV but I can only write to each row generated from my $contents array. What am I doing wrong?

PHP

$contents = array(date("Y").",".date("m").","."1st half,".$client.",".$resultcasa1.",".$billable_hours);

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=fms_usage.csv');

echo "Year, Month, Period, Client, Minutes Used, Billable Hours,";

$file = fopen("php://output", "w");

foreach($contents as $content){
     fputcsv($file,explode(',',$content));
}
fclose($file);

Output

Year  Month  Period  Client  Minutes Used  Billable Hours    2014   6   1st half    [email protected]  0   0
Year  Month  Period  Client  Minutes Used  Billable Hours    2014   6   1st half    [email protected]   0   0
Year  Month  Period  Client  Minutes Used  Billable Hours    2014   6   1st half    [email protected] 0   0
Year  Month  Period  Client  Minutes Used  Billable Hours    2014   6   1st half    tim 0   0
like image 300
Aaron Turecki Avatar asked Jun 12 '14 05:06

Aaron Turecki


2 Answers

You can use the same fputcsv function to output your headers too

Something like this...

$contents = [
  [2014, 6, '1st half', '[email protected]', 0, 0],
  [2014, 6, '1st half', '[email protected]', 0, 0],
  [2014, 6, '1st half', '[email protected]', 0, 0],
  [2014, 6, '1st half', 'tim', 0, 0]
];

$headers = ['Year', 'Month', 'Period', 'Client', 'Minutes Used', 'Billable Hours'];

$file = fopen("php://output", "w");

fputcsv($file, $headers);
foreach($contents as $content){
    fputcsv($file, $content);
}
fclose($file);

Demo here ~ https://eval.in/161434

like image 77
Phil Avatar answered Sep 26 '22 08:09

Phil


Or using fputcsv function :

$headers = "Year, Month, Period, Client, Minutes Used, Billable Hours";

$file = fopen("php://output", "w");

fputcsv($file, explode(', ', $headers));

....
like image 32
Vincent Decaux Avatar answered Sep 23 '22 08:09

Vincent Decaux