Copy Code code as follows:
<?php
$file = fopen (' text.csv ', ' R ');
while ($data = Fgetcsv ($file)) {//read one line in CSV every time
Print_r ($data); This is an array, to obtain each data, access to the array subscript can
$goods _list[] = $data;
}
Print_r ($goods _list);
echo $goods _list[0][1];
Fclose ($file);
?>
In actual work, many times need to download some data on the website to CSV file, convenient to view later.
Or use CSV to do some batch upload work.
This is when we need to read and write to CSV.
Read operations for CSV
Copy Code code as follows:
<?php
$file = fopen (' d:/file/file.csv ', ' R ');
while ($data = Fgetcsv ($file)) {//read one line in CSV every time
Print_r ($data); This is an array, to obtain each data, access to the array subscript can
}
Fclose ($file);
?>
<?php $file = fopen (' d:/file/file.csv ', ' R '); while ($data = Fgetcsv ($file)) {//Print_r ($DATA) for each line of content in CSV;//This is an array, to obtain each data, access the array subscript can be} fclose ($file);?>
Write operations for CSV
Copy Code code as follows:
<?php
$fp = fopen (' d:/file/file.csv ', ' W ');
Fputcsv ($fp, Array (' AAA ', ' BBB ', ' CCCC '));
Fputcsv ($fp, Array (' mmm ', ' yyy ', ' haha ')); Fputcsv can be implemented in the form of array loops
Fclose ($FP);
?>
<?php $fp = fopen (' d:/file/file.csv ', ' W '); Fputcsv ($fp, Array (' AAA ', ' BBB ', ' CCCC ')); Fputcsv ($fp, Array (' mmm ', ' yyy ', ' haha ')); Fputcsv can be implemented in the form of array loops fclose ($FP);?>
Output csv (download function)
Copy Code code as follows:
<?php
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 ";