2014-06-12 41 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