The following is a detailed analysis of the csv file reading, writing, and output downloading operations in php. if you need a friend, refer
The code is as follows:
$ File = fopen('text.csv ', 'r ');
While ($ data = fgetcsv ($ file) {// read the contents of a row in the CSV each time.
// Print_r ($ data); // This is an array. to obtain each data, access the array subscript.
$ Goods_list [] = $ data;
}
// Print_r ($ goods_list );
Echo $ goods_list [0] [1];
Fclose ($ file );
?>
In practice, you often need to download some data from the website to a CSV file for later viewing.
Or use CSV to upload data in batches.
In this case, we need to read and write CSV files.
CSV read operations
The code is as follows:
$ File = fopen ('d:/file/file.csv ', 'r ');
While ($ data = fgetcsv ($ file) {// read the contents of a row in the CSV each time.
Print_r ($ data); // This is an array. to obtain each data, access the array subscript.
}
Fclose ($ file );
?>
CSV write operation
The code is as follows:
$ Fp = fopen ('d:/file/file.csv ', 'w ');
Fputcsv ($ fp, array ('AAA', 'BBB ', 'cccccc '));
Fputcsv ($ fp, array ('mmm', 'yyy', 'hahaha'); // fputcsv can be implemented through array loops.
Fclose ($ fp );
?>
Output CSV (download function)
The code is as follows:
Header ("Content-Type: text/csv ");
Header ("Content-Disposition: attachment; filename=test.csv ");
Header ('cache-Control: must-revalidate, post-check = 0, pre-check = 0 ');
Header ('expires: 0 ');
Header ('pragma: public ');
Echo "id, areaCode, areaName/n ";
Echo "1, cn, china/n ";
Echo "2, us, America/n ";
?>
Output excel (download function)
Header("Content-type: application/vnd. ms-excel ");
Header("Content-Disposition: filename =Php100.xls");
Echo"Id, areaCode, areaName/n ";
Echo"1, cn, china/n ";
Echo"2, us, America/n ";