• fgetcsv读取中文的问题


    在使用fgetcsv读取文件内容,但是中文部分总是无法显示,如果一段文字中夹杂着字母和中文,则字母前的中文无法读取,但字母后的中文却能够保留。

    第一种解决办法:
    上PHP官網翻了一下,原來加上setlocale即可解決。
    原本用PHP4沒出現這問題,大概是PHP5才會這樣吧...

    注释:setlocale() 函数仅针对当前脚本改变地区信息。

    提示:可以通过 setlocale(LC_ALL,NULL) 把地区信息设置为系统默认。

    // utf-8
    setlocale(LC_ALL, 'en_US.UTF-8');
    // 简体
    setlocale(LC_ALL, 'zh_CN');

    //设置回系统默认

            setlocale(LC_ALL,NULL);

    以下是常用的地区标识

    zh_CN GB2312
    en_US.UTF-8 UTF-8
    zh_TW BIG5
    zh_HK BIG5-HKSCS
    zh_TW.EUC-TW EUC-TW
    zh_TW.UTF-8 UTF-8
    zh_HK.UTF-8 UTF-8
    zh_CN.GBK GBK

    第二种解决办法:(替代函数, 执行效率低)
    php自带的fgetcsv函数对中文支持总出问题,处理中文文档时,经常出现中文字符串丢字或乱码的情况。但找了个替代函数:
    function fgetcsv_reg(& $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;
    }

  • 相关阅读:
    详解Linux 安装 JDK、Tomcat 和 MySQL(图文并茂)
    详解Linux 安装 JDK、Tomcat 和 MySQL(图文并茂)
    常见的面试C#技术题目
    Struts2中的ModelDriven机制及其运用
    Struts2 中的数据传输的几种方式
    Struts2 中的数据传输的几种方式
    form表单中method的get和post区别
    form表单中method的get和post区别
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
  • 原文地址:https://www.cnblogs.com/ybbqg/p/2399659.html
Copyright © 2020-2023  润新知