Linux下使用fgetcsv()读取csv文件遇到的乱码问题
1、今日一项目需要通过上传CSV文件是想批量导入,于是用到了fgetcsv() 函数,函数代码如下:
<?php
$row = 1;
$handle = fopen("ceshi_1.csv","r");
while ($data = fgetcsv($handle, 1000, ",")) {
//$num = count($data);
$num = 29;
echo "<p> $num fields in line $row: <br>\n";
$row++;
for ($c=0; $c < $num; $c++) {
$data[$c]=iconv("gbk", "utf-8//IGNORE",$data[$c]);
echo $data[$c] . "<br>\n";
}
if (!$data[0] && !$data[1] && !$data[2]) break;
}
fclose($handle);
?>
2、上面代码在本地测试一点都没问题,但传到服务器(Linux)上则会出现汉字乱码问题,花了好久时间,在网上终于找到了解决办法,大概有两种:
一、使用PHP自定义处理.csv文件的函数:
/**
* 对CSV进行处理
* @param resource handle
* @param int length
* @param string delimiter
* @param string enclosure
* @return 文件内容或FALSE。
*/
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;
}
二、使用: setlocale 函数设置环境变量。:
设置setlocale(LC_ALL,'zh_CN');
做项目涉及到繁体的文档,就整个简体繁体都加上,应该影响不会很大:setlocale(LC_ALL,'zh_CN');
我选择了第2个方法,确实可行,第1个方法没有测试