2014-06-12 59 views
4

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

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 

回答

5

您可以使用相同的fputcsv功能输出你的头太

事情是这样的......

$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

4

或者用fputcsv功能:

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

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

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

.... 
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); 
+0

的第二个参数'fputcsv'应该是一个数组。你在这两个实例中传递一个字符串 – Phil

+0

好的,谢谢我改变了它... – Vishal