stack
stack

Reputation: 10228

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?

Upvotes: 0

Views: 1297

Answers (1)

Rajesh Patel
Rajesh Patel

Reputation: 2036

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

Upvotes: 1

Related Questions