欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

fgetcsv函数读取csv文件中文字符串的问题

程序员文章站 2022-06-08 12:50:15
...

读取csv文件数据函数:

  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"); /*要将gbk码转为utf-8,否则会出现乱码*/
  8. }
  9. $arr[] = $tmp;
  10. }
  11. }
  12. return $arr;
  13. }
复制代码

发现读取的中文字符串为空....

解决方法:将fgetcsv函数换成自定义的_fgetcsv函数

  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 $_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1' , $_csv_data[$_csv_i]);
  17. $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
  18. }
  19. return empty ($_line) ? false : $_csv_data;
  20. }
复制代码