php - How can I set column name as the name of .csv file's column? -
i have code creates .csv
export of table. here 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); ( $i = 0; $i < $size_of_outer_array; $i++ ) { $newarr[] = implode(",",$arr[$i]); } $fp = fopen('php://output', 'w'); foreach ( $newarr $line ) { $val = explode(",", $line); fputcsv($fp, $val); } fclose($fp); }
it works well, when import again, looks this:
as see, column names aren't real .. col1
, col2
, etc ..! need set names column names. id
, name
, etc ..!
how can that?
try
$fp = fopen('php://output', 'w'); fputcsv($fp, array('column 1', 'column 2', 'column 3')); foreach ( $newarr $line ) { $val = explode(",", $line); fputcsv($fp, $val); } fclose($fp);
Comments
Post a Comment