php - 将列标题写入CSV

时间:2014-06-12 05:48:03

标签: php csv

我有一个名为$ 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    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

3 个答案:

答案 0 :(得分:6)

您也可以使用相同的fputcsv功能输出标题

像这样......

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

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

答案 1 :(得分:4)

或使用fputcsv函数:

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

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

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

....

答案 2 :(得分:1)

$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);
相关问题