Home >Backend Development >PHP Tutorial >Example code for reading csv file contents with PHP_PHP tutorial
Read the data of all rows in the csv file at one time
$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 obtain 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);
?>
Read a certain row 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; //www.jbxue.com
$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);
?>
Read the csv file and 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 $ling[] = $out;
}
if ($line_end == $n) break;
}
fclose($handle);
}
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."
";
}
?>
Two other methods found online (haven’t tested it, so I don’t know if it works)
$handle=fopen("1.csv","r");
while(!feof($handle)){
$buffer=fgetss($handle,2048);
$ data=explode(",",$buffer);
$num=count($data);
for($i=0;$iprint_r($ data);
}
}
?>
Code 2,
$handle=fopen("1.csv","r");
$row=1;
while($data=fgetcsv($handle,1000,", ")){
$num=count($data);
for($i=0;$iecho $data[$i];
}
$row++;
}
?>