我有一个名为$ contents的数组,可以遍历并写入CSV。我想将列标题写到CSV的顶部,但是我只能写从$ contents数组生成的每一行。我究竟做错了什么?

的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);

输出
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

最佳答案

您也可以使用相同的fputcsv函数输出 header

像这样的东西

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

在这里演示〜https://eval.in/161434

10-08 13:36