当前位置:Gxlcms > PHP教程 > fgetcsv函数读取csv文件中文字符串的问题

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

时间:2021-07-01 10:21:17 帮助过:8人阅读

读取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 < 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. }

人气教程排行