gpt4 book ai didi

php - 将列标题写入 CSV

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:00:46 26 4
gpt4 key购买 nike

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

最佳答案

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

像这样的……

$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

关于php - 将列标题写入 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24177265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com