Home  >  Article  >  Backend Development  >  Detailed explanation of reading csv file content based on PHP_PHP tutorial

Detailed explanation of reading csv file content based on PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:05:31888browse

Read the data of all rows in the csv file at one time

Copy the code The code is as follows:

< ;?php
$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
Copy the code The code is as follows:

function get_file_line( $file_name, $line ){
$n = 0;
$handle = fopen($file_name,'r');
if ($handle) {
while (! feof($handle)) {
++$n;
$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 to specify the number of lines (line interval)
Copy code The code is as follows:

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);
}
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, don’t know if it works)
Copy Code The code is as follows:

$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 The code is as follows:

$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++;
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327695.htmlTechArticleRead the data of all rows in the csv file at one time and copy the code as follows: ?php $file = fopen(' windows_2011_s.csv','r'); while ($data = fgetcsv($file)) { //Read one line in the CSV each time...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn