Question about reading Chinese strings from csv files using the fgetcsv function
|
Functions for reading csv file data:
- Function getData ($ file ){
- $ Arr = array ();
- If ($ handle = fopen ($ file, "r "))! = FALSE ){
- While ($ data = fgetcsv ($ handle ))! = FALSE ){
- $ Tmp = array ();
- Foreach ($ data as $ key => $ v ){
- $ Tmp [] = mb_convert_encoding ($ v, "UTF-8", "gbk");/* convert gbk to UTF-8, otherwise garbled characters */
- }
- $ Arr [] = $ tmp;
- }
- }
- Return $ arr;
- }
The Chinese string read is found to be null ....
Solution: replace the fgetcsv function with the custom _ fgetcsv function.
- 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;
- }
|