$file = $_FILES[‘file’];
$file_name = $file[‘tmp_name’];
if($file_name == '') {
$this->error("请选择要上传的csv文件");
}
// 以只读的方式打开文件
$handle = fopen($file_name, 'r');
if($handle === FALSE) {
$this->error("打开文件资源失败");
}
// 删除上传文件
unlink($file_name);
// setlocale() 函数设置地区信息(地域信息)。
@setlocale(LC_ALL, 'zh_CN');
// CSV对应的字段名
$csv_val = array('name', 'email', 'mobile', 'department', 'feedback_name', 'feedback_email', 'feedback_mobile', 'feedback_department', 'level');
$data = array();
while(($row = fgetcsv($handle)) !== FALSE) {
//解决中文乱码
$row = eval('return '.iconv('gbk','utf-8',var_export($row,true)).';');
//这里需要检查和给的字段数是否一致,如果不一致,则不能写入
$tmp_row = array();
foreach ($csv_val as $k => $v) {
$row_value = ltrim($row[$k], '`');
$encode = mb_detect_encoding($row_value, array("ASCII", "UTF-8", "GB2312", "GBK", "BIG5"));
if( $encode!="UTF-8" ){
$tmp_row[$v] = trim(iconv($encode,'UTF-8//IGNORE', $row_value));
}else{
$tmp_row[$v] = trim($row_value);
}
}
$data[] = $tmp_row;
}
// 关闭资源
fclose($handle);