In other windows versions
| The code is as follows: |
Copy code |
|
# Open the File.
If ($ handle = fopen ("test.csv", "r "))! = FALSE ){
# Set the parent multidimen1_array key to 0.
$ Nn = 0;
While ($ data = fgetcsv ($ handle, 0 ,","))! = FALSE ){
// Print_r ($ data );
# Count the total keys in the row.
$ C = count ($ data );
# Populate the multidimen1_array.
For ($ x = 0; $ x <$ c; $ x ++)
{
$ Csvarray [$ nn] [$ x] = $ data [$ x];
}
$ Nn ++;
}
# Close the File.
Fclose ($ handle );
}
// Print_r ($ csvarray ); |
There is no problem with this code. Then I put it in linux and found that there are null fields.
The data parsed by the problem is incomplete and there are blank fields.
I found a bug in php5.2.8 on the Internet.
The solution is to use a UDF.
| The code is as follows: |
Copy code |
|
Function _ fgetcsv (& $ handle, $ length = null, $ d = ',', $ e = '"'){
$ D = preg_quote ($ d );
$ E = preg_quote ($ e );
$ _ Line = "";
$ Eof = false;
While ($ eof! = True ){
$ _ Line. = (empty ($ length )? Fgets ($ handle): fgets ($ handle, $ length ));
$ Itemcnt = preg_match_all ('/'. $ e. '/', $ _ line, $ dummy );
If ($ itemcnt % 2 = 0)
$ Eof = true;
}
$ _ Csv_line = preg_replace ('/(? : | [])? $/', $ D, trim ($ _ line ));
$ _ Csv_pattern = '/('. $ e. '[^'. $ e. '] * (? :'. $ E. $ e. '[^ '. $ e. '] *) *'. $ e. '| [^ '. $ d. '] *)'. $ d. '/';
Preg_match_all ($ _ csv_pattern, $ _ csv_line, $ _ csv_matches );
$ _ Csv_data = $ _ csv_matches [1];
For ($ _ csv_ I = 0; $ _ csv_ I <count ($ _ csv_data); $ _ csv_ I ++ ){
$ _ Csv_data [$ _ csv_ I] = preg_replace ('/^ '. $ e. '(. *)'. $ e. '$/S',' $ 1', $ _ csv_data [$ _ csv_ I]);
$ _ Csv_data [$ _ csv_ I] = str_replace ($ e. $ e, $ e, $ _ csv_data [$ _ csv_ I]);
}
Return empty ($ _ line )? False: $ _ csv_data;
} |