1
2<?php
3$row = 1;
4if (($handle = fopen("test.csv", "r")) !== FALSE) {
5 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
6 $num = count($data);
7 echo "<p> $num fields in line $row: <br /></p>\n";
8 $row++;
9 for ($c=0; $c < $num; $c++) {
10 echo $data[$c] . "<br />\n";
11 }
12 }
13 fclose($handle);
14}
15?>
16
17
1 $csvFile = file('../somefile.csv');
2 $data = [];
3 foreach ($csvFile as $line) {
4 $data[] = str_getcsv($line);
5 }
1<?php
2ini_set('auto_detect_line_endings',TRUE);
3$handle = fopen('/path/to/file','r');
4while ( ($data = fgetcsv($handle) ) !== FALSE ) {
5 //process the array in $data
6 var_dump($data);
7}
8ini_set('auto_detect_line_endings',FALSE);
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?>
1// output headers so that the file is downloaded rather than displayed
2header('Content-Type: text/csv; charset=utf-8');
3header('Content-Disposition: attachment; filename=data.csv');
4
5// create a file pointer connected to the output stream
6$output = fopen('php://output', 'w');
7
8// output the column headings
9fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
10
11// fetch the data
12mysql_connect('localhost', 'username', 'password');
13mysql_select_db('database');
14$rows = mysql_query('SELECT field1,field2,field3 FROM table');
15
16// loop over the rows, outputting them
17while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
18