Home > Backend Development > PHP Tutorial > Problem with fgetcsv function reading Chinese strings from csv files

Problem with fgetcsv function reading Chinese strings from csv files

WBOY
Release: 2016-07-25 09:13:11
Original
1365 people have browsed it

Read csv file data function:

  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 code to utf-8, otherwise garbled characters will appear*/
  8. }
  9. $arr[] = $tmp;
  10. }
  11. }
  12. return $arr;
  13. }
Copy code

Found that the Chinese string read is empty....

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 . '/' ; _ Preg_Match_all ($ _ csv_pattern, $ _CSV_LINE, $ _CSV_Matches);
  14. $ _csv_data = $ _CSV_Matches [1]; nt ($ _ csv_data); $ _csv_i ++) {
  15. $ _csv_data [ $_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1' , $_csv_data[$_csv_i]);
  16. $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
  17. }
  18. return empty ($_line) ? false : $_csv_data;
  19. }
Copy code
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template