php获取csv数据无乱码

本文介绍了一种从CSV文件中读取数据并将其转换为UTF-8编码的方法。通过PHP脚本实现了文件上传、内容读取、编码检测及转换等功能。适用于需要处理多种编码CSV文件的场景。

<?php

 //获取csv数据
    function csvencode($file){
        if(!is_file($file['tmp_name'])){
            return;
        }
        $handle=fopen($file['tmp_name'],'r');

        $content = fread($handle, filesize($file['tmp_name']));
        $content = convert2utf8($content);

        $data=explode("\n",$content);

        $i=1;
        $arr=array();
        foreach($data as $o){

            if(!ctype_space($o) && !empty($o)){

                $arr[$i]=explode(',',$o);
                $i++;
            }


        }

        return $arr;

    }

    //转换为utf8编码
    function convert2utf8($content)
    {


        mb_detect_order("UTF-8, GBK, ISO-8859-1"); //探测顺序
        $encoding = mb_detect_encoding($content);//获取编码
        if ($encoding && strtolower($encoding) !== 'utf-8') {
            $content = iconv($encoding, 'UTF-8//IGNORE', $content);
        }
        return $content;
    }

转载于:https://www.cnblogs.com/myphper/p/3760652.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值