Solve the problem that php fgetcsv reads csv file data is incomplete

Source: Internet
Author: User

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;
}

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.