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*/
1To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on failure.
2
3Syntax :
4
5fputcsv( file, fields, separator, enclosure, escape )
6
7Example:
8<?php
9
10// Create an array of elements
11$list = array(
12 ['Name', 'age', 'Gender'],
13 ['Bob', 20, 'Male'],
14 ['John', 25, 'Male'],
15 ['Jessica', 30, 'Female']
16);
17
18// Open a file in write mode ('w')
19$fp = fopen('persons.csv', 'w');
20
21// Loop through file pointer and a line
22foreach ($list as $fields) {
23 fputcsv($fp, $fields);
24}
25
26fclose($fp);
27?>