"John", "Gend-6ren">
gpt4 book ai didi

php - 使用 PHP 创建 CSV 文件

转载 作者:行者123 更新时间:2023-12-02 00:52:21 26 4
gpt4 key购买 nike

我想创建一个新的 .csv 文件(无需先通过 fopen 打开原始文件)。到目前为止,我已经试过了:

$list[] = array
(
"Name" => "John",
"Gender" => "M",
"Age" => "21"
);
$timestamp0 = date("Y-m-d H:i:sa", time());
$datetime = new DateTime($timestamp0);
$datetime->setTimezone(new DateTimeZone('Asia/Jakarta'));
$timestamp = $datetime->format("Y-m-d_H-i");

$filename = __DIR__ . "/file/" . $timestamp . ".csv";

$header = array("name", "gender", "age");
file_put_contents($filename, implode("\n", $list)); // error here bcs array given :')

我的问题是:

  1. How can I change array 2d to csv?

非常需要您的帮助 :( 非常感谢 :")

最佳答案

使用 fopen如果文件不存在,with w 将创建文件:

$list = [
["Name" => "John", "Gender" => "M"],
["Name" => "Doe", "Gender" => "M"],
["Name" => "Sara", "Gender" => "F"]
];

$fp = fopen($filename, 'w');
//Write the header
fputcsv($fp, array_keys($list[0]));
//Write fields
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);

如果你不喜欢fputcsvfopen您可以使用此替代方法:

$list = [
["Name" => "John", "Gender" => "M"],
["Name" => "Doe", "Gender" => "M"],
["Name" => "Sara", "Gender" => "F"]
];

$csvArray = ["header" => implode (",", array_keys($list[0]))] + array_map(function($item) {
return implode (",", $item);
}, $list);

file_put_contents($filename, implode ("\n", $csvArray));

希望对您有所帮助。

关于php - 使用 PHP 创建 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38690756/

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