之前有写过用插件导入xlsx文件的方法,但是那个需要第三方插件,在某些项目里面不是很适用,所以这里介绍一种csv文件的导入方式。csv可以通过xlsx文件直接转换,很方便。
/**
* @param string $file 文件地址
* @param array $filed 预设字段,设置好这个,第一行数据会自动加上对应的key
* @param int $line 读取几行
* @param int $offset 偏移量
* @return array|string
*/
private function csvHandle(string $file = '', $filed=['gif', 'title'], $line=0, $offset=1)
{
setlocale(LC_ALL, 'zh_CN');
$handle = fopen($file,'r');
if(!$handle){
return '文件打开失败';
}
$i = 0;
$arr = [];
while($data = fgetcsv($handle)){
$j = 0;
//小于偏移量则不读取,但$i仍然需要自增
if($i < $offset && $offset){
$i++;
continue;
}
//大于读取行数则退出
if($i > $line && $line){
break;
}
$tmp = [];
foreach ($data as $key => $value) {
//$content = iconv("gbk","utf-8//IGNORE",$value);//转化编码
$content = $this->convertToUTF8($value);
//$arr[][$filed[$j]] = $content;
$tmp[$filed[$j]] = $content;
$j++;
}
$arr[] = json_encode($tmp);
$i++;
}
return $arr;
}
private function convertToUTF8($text){
$encoding = mb_detect_encoding($text, mb_detect_order(), true);
if($encoding == "UTF-8")
{
$text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
}
if ($encoding === false) {
$encoding = 'GBK';//短字符串无法判断字符串类型。。一般是文字出现这种问题,所以设置为gbk
}
$out = iconv($encoding, "UTF-8//IGNORE", $text);
return $out;
}
0 条评论