Create CSV File with PHP

放肆的年华 提交于 2019-12-02 13:19:04

Using fopen with w will create the file if does not exist:

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

If you don't like fputcsv and fopen you can use this alternative:

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

I hope this will help you.

You can use below code

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

For more detail read php manual about CSV file. http://php.net/manual/en/function.fputcsv.php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!