'Export Data to CSV or Excel Laravel [duplicate]

I have this Data Array like this

I have stored this value in $data variable

enter image description here

I want to export this data into Excel or CSV

I have tried multiple ways & checked a lot articles but still can't find anything



Solution 1:[1]

You can use plain PHP only without any lib to create csv file. I took a test array for the example below.

The important step is only to convert your array in a comma separated string.

example

<?php

$arr = [
    [
        "id" => 1, "name" => "abc"
    ],
    [
        "id" => 2, "name" => "def"
    ],  
];

$data = [];
foreach($arr as $val) {
    $str = implode(',', $val );
    $data[] = $str;
}

$handle = fopen('export.csv', 'w');

foreach ($data as $row) {
    fputcsv($handle, $row);
}

fclose($handle);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maik Lowrey