-
- $file = fopen('windows_2011_s.csv','r');
- while ($data = fgetcsv($file)) { //Read one line of content in CSV each time
- //print_r($data); //This is an array. To get each data, just access the array subscript
- $goods_list[] = $data;
- }
- //print_r($goods_list);
- / * foreach ($goods_list as $arr){
- if ($arr[0]!=""){
- echo $arr[0]."
";
- }
- } */
- echo $goods_list[ 2][0];
- fclose($file);
- ?>
Copy the code
Example 2, read a certain line of data from the csv file.
-
- function get_file_line( $file_name, $line ){
- $n = 0;
- $handle = fopen($file_name,'r');
- if ($handle) {
- while (!feof($handle)) {
- ++$n; // bbs.it-home.org
- $out = fgets($handle, 4096);
- if($line==$n) break;
- }
- fclose($handle);
- }
- if( $line==$n) return $out;
- return false;
- }
- echo get_file_line("windows_2011_s.csv", 10);
- ?>
Copy Code
Example 3, read the csv file to specify the number of lines (line interval).
-
- function get_file_line( $file_name, $line_star, $line_end){
- $n = 0;
- $handle = fopen($file_name,"r");
- if ($handle) {
- while (!feof($handle)) {
- ++$n;
- $out = fgets($handle, 4096);
- if($line_star <= $n){
- $ling[] = $out ;
- }
- if ($line_end == $n) break;
- }
- fclose($handle);
- } // bbs.it-home.org
- if( $line_end==$n) return $ling;
- return false;
- }
- $aa = get_file_line("windows_2011_s.csv", 11, 20); //From line 11 to line 20
- foreach ($aa as $bb){
- echo $bb."< br>";
- }
- ?>
Copy code
Example 4, two methods provided by netizens, untested.
method 1,
-
- //Read the contents of the csv file
- $handle=fopen("1.csv","r");
- while(!feof($handle)){
- $buffer= fgetss($handle,2048);
- $data=explode(",",$buffer);
- $num=count($data);
- for($i=0;$i<$num;$i++){
- print_r($data);
- }
- }
- ?>
Copy code
Method 2,
-
- //Read the contents of the csv file
- $handle=fopen("1.csv","r");
- $row=1;
- while($data=fgetcsv($ handle,1000,",")){
- $num=count($data);
- for($i=0;$i<$num;$i++){
- echo $data[$i];
- }
- $row++;
- }
- ?>
Copy code
|