stack stack - 29 days ago 16
PHP Question

How can I set column name as the name of .csv file's column?

I have a code which creates a

.csv
export of my table. Here is my code:

public function export(Request $request){

header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="export.csv"');

$tb_name_alias = $request->tb_name;
$convert_alias_to_table_name = array('person' => "App\\persons");
$tb_name = $convert_alias_to_table_name[$tb_name_alias];
$arr = $tb_name::all()->toArray();

$newarr = array();
$size_of_outer_array = sizeof($arr);

For ( $i = 0; $i < $size_of_outer_array; $i++ ) {
$newarr[] = implode(",",$arr[$i]);
}

$fp = fopen('php://output', 'w');
foreach ( $newarr as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
}


It works as well, But when I import it again, it looks like this:

enter image description here

As you see, the column names aren't real .. they are
col1
,
col2
, etc ..! But I need to set some names as those column names. Like
id
,
name
, etc ..!

How can I do that?

Answer

try this

$fp = fopen('php://output', 'w');
fputcsv($fp, array('Column 1', 'Column 2', 'Column 3'));


 foreach ( $newarr as $line ) {
        $val = explode(",", $line);
        fputcsv($fp, $val);
    }
    fclose($fp);