I want to create a new .csv file (without opening the raw file first via fopen). So far I have tried this:
$list[] = array
(
"Name&q
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.