0

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

newdevv2
  • 201
  • 3
  • 10
  • 2
    *"I have tried multiple ways & checked a lot articles but still can't find anything"* for real? you didnt even stumble upon [fputcsv](https://www.php.net/manual/en/function.fputcsv.php)? not even [this qa](https://stackoverflow.com/questions/16251625/how-to-create-and-download-a-csv-file-from-php-script)? not even a stroll on `packagist`? – Bagus Tesa Apr 30 '22 at 13:55

1 Answers1

0

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);
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79