search

Home  >  Q&A  >  body text

iconv - PHP中UTF8和UTF-8可以混用吗?

同事使用iconv进行编码转换时使用的时UTF8,而不是UTF-8,我测试了下发现UTF8和UTF-8在iconv和mb_str中结果是一样的,如: iconv('UTF8', 'GB2312', '测试');iconv('UTF-8', 'GB2312', '测试');。但是Google了下发现也有人因为使用UTF8而不是UTF-8遇到问题的情况 http://readyfighting.com/archives/156。

那么请问二者使用起来有什么不同吗?

PHPzPHPz2894 days ago609

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-10 13:13:50

    根据 libiconv-1.14/lib/encodings.def , UTF-8和UTF8都会被识别成utf8编码,所以没有区别,所以所有使用libiconv的程序都没问题,比如php的iconv库。

    /* General multi-byte encodings */
    
    DEFENCODING(( "UTF-8",                  /* IANA, RFC 2279 */
                /*"UTF8",                      JDK 1.1 */
                /*"CP65001",                   Windows */
                ),   
                utf8,
                { utf8_mbtowc, NULL },        { utf8_wctomb, NULL })
    #ifdef USE_HPUX_ALIASES
    DEFALIAS(     "UTF8",                   /* HP-UX */
                utf8)
    #endif

    根据 ext/mbstring 的 mbfilter_utf8.c ,UTF-8 (作为name/mimename) 和 UTF8 (作为alias)也都可以被识别,所以也一样。

    static const char *mbfl_encoding_utf8_aliases[] = {"utf8", NULL};
    
    const mbfl_encoding mbfl_encoding_utf8 = { 
        mbfl_no_encoding_utf8,
        "UTF-8",
        "UTF-8",
        (const char *(*)[])&mbfl_encoding_utf8_aliases,
        mblen_table_utf8,
        MBFL_ENCTYPE_MBCS
    };

    顺便说一下,mysql不识别 utf-8,必须用utf8。

    mysql> create table t1 (id int primary key, name int) character set utf-8;
    ERROR 1115 (42000): Unknown character set: 'utf'

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 13:13:50

    你好,我在windows环境下测试了一行代码

    iconv('UTF8', 'GB2312', '测试');

    得到一个警告

    Notice: iconv(): Wrong charset, conversion from `UTF8' to `GB2312' is not allowed

    这说明应该使用UTF-8这种形式才是正确的。

    mbstring.supported-encodings 提到的mbstring支持的编码中也只有UTF-8这种形式。

    或许是你可以尝试修改一下php.ini

    error_reporting = E_ALL | E_STRICT
    display_errors = On

    也许就可以看到警告信息了。

    根据felix021的提示,再测试两行代码

    print_r(mb_list_encodings());
    print_r(mb_encoding_aliases('UTF8'));

    可知mb中的确是做为别名处理了。

    reply
    0
  • Cancelreply