[英]php - writing column headers to CSV
I have an array called $contents which I loop through and write to CSV. 我有一个名为$ contents的数组,我循环并写入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.
我想将列标题写在CSV的顶部,但我只能写入从$ contents数组生成的每一行。 What am I doing wrong?
我究竟做错了什么?
PHP 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 您也可以使用相同的
fputcsv
函数输出标题
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 在这里演示~ https://eval.in/161434
Or using fputcsv function : 或者使用fputcsv函数:
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.