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
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
Or using fputcsv function :
$headers = "Year, Month, Period, Client, Minutes Used, Billable Hours";
$file = fopen("php://output", "w");
fputcsv($file, explode(', ', $headers));
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With