php导入csv文件输出是乱码,怎么解决
发布网友
发布时间:2022-04-06 03:46
我来回答
共1个回答
热心网友
时间:2022-04-06 05:15
//这是我前几天回答过的一个问题下面以读取淘宝csv文件为例
if($result){ //如果上传成功了,这是文件路径
if (!($handle = fopen_utf8($result, "r")) === FALSE){ //调取下边函数fopen_utf8;
$errorArr = array();
$i=0;
while (($cols = fgetcsv($handle, 1000, "\t")) !== FALSE) {
++$i;
if($i<4) continue;
$taobaolmsx = $cols[21];//宝贝属性;
$taobaoxxsx = $cols[30];//销售属性;
$goodsBn = $cols[33];//商家编码;
}
fclose($handle);
}
unlink($result);
}else{
echo 'file upload error';exit;
}
/*读取csv文件用 */
function fopen_utf8($filename){
$encoding='';
$handle = fopen($filename, 'r');
$bom = fread($handle, 2);
rewind($handle);
if($bom === chr(0xff).chr(0xfe) || $bom === chr(0xfe).chr(0xff)){
// UTF16 Byte Order Mark present
$encoding = 'UTF-16';
} else {
$file_sample = fread($handle, 1000) + 'e'; //read first 1000 bytes
// + e is a workaround for mb_string bug
rewind($handle);
$encoding = mb_detect_encoding($file_sample , 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
}
if ($encoding){
stream_filter_append($handle, 'convert.iconv.'.$encoding.'/UTF-8');
}
return ($handle);
}
追问
执行到while (($cols = fgetcsv($handle, 1000, "\t")) !== FALSE)时$cols为false,不晓得是什么情况,代码如图:
请指教~谢谢!!
追答
下载这个文件测试,用我发你的代码,先看能不能成功。