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

发布时间:2019-12-11编辑:脚本学堂
本文介绍了fgetcsv函数不能读取csv文件中文字符串的解决方法,有关fgetcsv函数的用法,有需要的朋友参考下。

读取csv文件数据函数:
 

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

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

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

复制代码 代码示例:
    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;
    }