V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
darasion
V2EX  ›  问与答

怎样让 php 的 json_encode() 兼容任何编码?

  •  
  •   darasion · Jul 9, 2011 · 4959 views
    This topic created in 5410 days ago, the information mentioned may be changed or developed.
    事情是这样的

    json_encode() 只支持兼容utf-8编码的东西。如果不是就会报错500.。

    要编成 json 传输到浏览器端,输入数据的编码可能是随机的任何编码,要让这些内容正常显示。
    8 replies    1970-01-01 08:00:00 +08:00
    TheOnly92
        1
    TheOnly92  
       Jul 9, 2011
    mb_convert_encoding($input, 'UTF-8')
    darasion
        2
    darasion  
    OP
       Jul 9, 2011
    @TheOnly92 这个函数试过,但是它却把正常能显示的东西编码成什么都看不清的乱码了。。。
    TheOnly92
        3
    TheOnly92  
       Jul 9, 2011
    你应该至少控制一下输入数据的编码,在 <head> 内加 <meta charset> 输入进来的就都是 UTF-8 了,还是说这些数据是前人留下来的?
    darasion
        4
    darasion  
    OP
       Jul 9, 2011
    @TheOnly92 呵呵,需求特殊,这个是从海量文件里 cat 出来的内容,事先不可能知道是什么编码。也许编码根本不符合规则。要做个很智能,很兼容的东西出来..
    TheOnly92
        5
    TheOnly92  
       Jul 9, 2011
    如果要编成 json 的数据不是很复杂,就用 $out = '["' . implode('","', $return_arr) . '"]'; 这样简单的就行了吧。否则就得想办法把所有数据转变为 UTF-8
    darasion
        6
    darasion  
    OP
       Jul 9, 2011
    @TheOnly92 ...很不幸,两个条件都无法满足。

    一、很复杂;
    二、没办法都变utf8。

    算了,这个问题我还是搁置吧....
    darasion
        7
    darasion  
    OP
       Jul 9, 2011
    我换个角度来问:

    mb_detect_encoding($str, array('gbk','utf-8',..........)) 这个函数,以什么样的判断顺序为佳?

    有种如果 我把 utf-8放在 gbk的前边,那么很多时候gbk会被判断成utf-8, 最终给json_encode编码还是会出错。 如果我把gbk放在前边,那么会不会utf-8被判断成gbk?

    怎样的顺序才能兼容所有编码?
    TheOnly92
        8
    TheOnly92  
       Jul 9, 2011
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2509 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 12:16 · PVG 20:16 · LAX 05:16 · JFK 08:16
    ♥ Do have faith in what you're doing.