1// open the file "demosaved.csv" for writing
2$file = fopen('demosaved.csv', 'w');
3
4// save the column headers
5fputcsv($file, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));
6
7// Sample data. This can be fetched from mysql too
8$data = array(
9array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
10array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
11array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
12array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
13array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55')
14);
15
16// save each row of the data
17foreach ($data as $row)
18{
19fputcsv($file, $row);
20}
21
22// Close the file
23fclose($file);
1$lines =file('CSV Address.csv');
2
3foreach($lines as $data)
4{
5list($name[],$address[],$status[])
6= explode(',',$data);
7}
8
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?>