Detailed description of csv file reading based on PHP
Source: Internet
Author: User
This article provides a detailed analysis of the contents of csv files read by PHP. For more information, see
Reads data from all rows in a csv file at a time. The code is as follows:
$ File = fopen('windows_201511s.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 );
/* Foreach ($ goods_list as $ arr ){
If ($ arr [0]! = ""){
Echo $ arr [0]."
";
}
}*/
Echo $ goods_list [2] [0];
Fclose ($ file );
?>
Reads a row of data from a csv file. 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_201511s.csv", 10 );
?>
Read csv files to specify the number of rows (row interval) 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_201511s.csv", 11, 20); // from 11th rows to 20th rows
Foreach ($ aa as $ bb ){
Echo $ bb ."
";
}
?>
In addition, you can find two methods on the Internet (I don't know whether to enable them) 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 );
}
}
?>
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 ++;
}
?>
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.