使用PHP创建CSV文件

时间:2016-08-01 03:53:35

标签: php csv export-to-csv

我想创建一个新的.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. 如何将数组2d更改为csv?
  2.   

非常需要你的帮助:(非常感谢你:“)

2 个答案:

答案 0 :(得分:2)

fopenargv一起使用将创建文件(如果不存在):

w

如果您不喜欢fputcsvfopen,可以使用此备选方案:

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

我希望这会对你有所帮助。

答案 1 :(得分:0)

您可以使用以下代码

$list[]=array ("name","gender","age"); // push header here
$list[] = array("John","M","21"); // push record here

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

$fp = fopen($filename, 'w');
foreach ($list as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);

有关CSV文件的详细信息,请参阅php手册。 http://php.net/manual/en/function.fputcsv.php