简体   繁体   中英

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    roland@fsjinvestor.com  0   0
Year  Month  Period  Client  Minutes Used  Billable Hours    2014   6   1st half    steve@neocodesoftware.com   0   0
Year  Month  Period  Client  Minutes Used  Billable Hours    2014   6   1st half    susanne@casamanager.com 0   0
Year  Month  Period  Client  Minutes Used  Billable Hours    2014   6   1st half    tim 0   0

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

Something like this...

$contents = [
  [2014, 6, '1st half', 'roland@fsjinvestor.com', 0, 0],
  [2014, 6, '1st half', 'steve@neocodesoftware.com', 0, 0],
  [2014, 6, '1st half', 'susanne@casamanager.com', 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

Or using fputcsv function :

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM