Aaron Turecki
Aaron Turecki

Reputation: 355

php - writing column headers to 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

Upvotes: 7

Views: 15754

Answers (3)

Vishal
Vishal

Reputation: 108

$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');

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

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

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

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

Upvotes: 1

Vincent Decaux
Vincent Decaux

Reputation: 10714

Or using fputcsv function :

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

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

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

....

Upvotes: 4

Phil
Phil

Reputation: 164766

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

Upvotes: 10

Related Questions