barney barney - 4 months ago 19
PHP Question

Create CSV File with PHP

I want to create a new .csv file (without opening the raw file first).
So far I have tried this:

$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 :')


My questions are:



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




Very need your help :( Thank you so much :")

Answer

You can try this:

$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("contacts-" . date("Y-m-d_H-i", time()) . ".csv", implode ("\n", $csvArray));

I hope this will help you.