1Instead of writing out values consider using 'fputcsv()'.
2
3This may solve your problem immediately.
4
5function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
6{
7 $f = fopen('php://memory', 'r+');
8 foreach ($data as $item) {
9 fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
10 }
11 rewind($f);
12 return stream_get_contents($f);
13}
14
15$list = array (
16 array('aaa', 'bbb', 'ccc', 'dddd'),
17 array('123', '456', '789'),
18 array('"aaa"', '"bbb"')
19);
20var_dump(array2csv($list));
21
22/*
23I hope it will help you.
24Namaste
25Stay Home Stay Safe
26*/
1/**
2 * Takes in a filename and an array associative data array and outputs a csv file
3 * @param string $fileName
4 * @param array $assocDataArray
5 */
6public function outputCsv($fileName, $assocDataArray)
7{
8 ob_clean();
9 header('Pragma: public');
10 header('Expires: 0');
11 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
12 header('Cache-Control: private', false);
13 header('Content-Type: text/csv');
14 header('Content-Disposition: attachment;filename=' . $fileName);
15 if(isset($assocDataArray['0'])){
16 $fp = fopen('php://output', 'w');
17 fputcsv($fp, array_keys($assocDataArray['0']));
18 foreach($assocDataArray AS $values){
19 fputcsv($fp, $values);
20 }
21 fclose($fp);
22 }
23 ob_flush();
24}
25// Call function
26 $allData = Subscription::all();
27 $data = array();
28 foreach ($allData as $key => $value)
29 {
30 $fields = array( 'S.No' => $value->id, 'Email' => $value->email, 'Date' => date('Y-m-d',strtotime($value->created_at)));
31 $data[] = $fields;
32 }
33 $filename = date('Y-m-d H:i:s').' - subcription_data.csv';
34 outputCsv($filename, $data);
35
36
37
38