Several examples of PHP reading csv file content
- $ 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 );
- ?>
Example 2: Read a row of data in a 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_201511s.csv", 10 );
- ?>
Example 3: Read the csv file to specify the number of rows (row 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_201511s.csv", 11, 20); // from 11th rows to 20th rows
- Foreach ($ aa as $ bb ){
- Echo $ bb ."
";
- }
- ?>
Example 4: two methods provided by netizens are not tested. 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 );
- }
- }
- ?>
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 ++;
- }
- ?>
|