Question about reading Chinese strings from csv files using the fgetcsv function

Source: Internet
Author: User
Question about reading Chinese strings from csv files using the fgetcsv function

Functions for reading csv file data:

  1. Function getData ($ file ){
  2. $ Arr = array ();
  3. If ($ handle = fopen ($ file, "r "))! = FALSE ){
  4. While ($ data = fgetcsv ($ handle ))! = FALSE ){
  5. $ Tmp = array ();
  6. Foreach ($ data as $ key => $ v ){
  7. $ Tmp [] = mb_convert_encoding ($ v, "UTF-8", "gbk");/* convert gbk to UTF-8, otherwise garbled characters */
  8. }
  9. $ Arr [] = $ tmp;
  10. }
  11. }
  12. Return $ arr;
  13. }

The Chinese string read is found to be null ....

Solution: replace the fgetcsv function with the custom _ fgetcsv function.

  1. Function _ fgetcsv (& $ handle, $ length = null, $ d = ',', $ e = '"'){
  2. $ D = preg_quote ($ d );
  3. $ E = preg_quote ($ e );
  4. $ _ Line = "";
  5. $ Eof = false;
  6. While ($ eof! = True ){
  7. $ _ Line. = (empty ($ length )? Fgets ($ handle): fgets ($ handle, $ length ));
  8. $ Itemcnt = preg_match_all ('/'. $ e. '/', $ _ line, $ dummy );
  9. If ($ itemcnt % 2 = 0)
  10. $ Eof = true;
  11. }
  12. $ _ Csv_line = preg_replace ('/(? : | [])? $/', $ D, trim ($ _ line ));
  13. $ _ Csv_pattern = '/('. $ e. '[^'. $ e. '] * (? :'. $ E. $ e. '[^ '. $ e. '] *) *'. $ e. '| [^ '. $ d. '] *)'. $ d. '/';
  14. Preg_match_all ($ _ csv_pattern, $ _ csv_line, $ _ csv_matches );
  15. $ _ Csv_data = $ _ csv_matches [1];
  16. For ($ _ csv_ I = 0; $ _ csv_ I <count ($ _ csv_data); $ _ csv_ I ++ ){
  17. $ _ Csv_data [$ _ csv_ I] = preg_replace ('/^ '. $ e. '(. *)'. $ e. '$/S',' $ 1', $ _ csv_data [$ _ csv_ I]);
  18. $ _ Csv_data [$ _ csv_ I] = str_replace ($ e. $ e, $ e, $ _ csv_data [$ _ csv_ I]);
  19. }
  20. Return empty ($ _ line )? False: $ _ csv_data;
  21. }

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.