Json_encode Charset problem

前端 未结 7 813
心在旅途
心在旅途 2020-12-10 17:35

When I use json_encode to encode my multi lingual strings , It also changes special characters.What should I do to keep them same .

For example

<         


        
相关标签:
7条回答
  • 2020-12-10 17:45
    <?php
    
    print_r(json_decode(json_encode(array('şüğçö'))));
    
    /*
    Array
    (   
        [0] => şüğçö
    )
    */
    

    So do you really need to keep these characters unescaped in the JSON?

    0 讨论(0)
  • 2020-12-10 17:53

    try it:

    <?
    echo json_encode(array('şüğçö'), JSON_UNESCAPED_UNICODE);
    
    0 讨论(0)
  • 2020-12-10 17:53

    PHP 5.4 adds the option JSON_UNESCAPED_UNICODE, which does what you want. Note that json_encode always outputs UTF-8.

    0 讨论(0)
  • 2020-12-10 17:57

    In JSON any character in strings may be represented by a Unicode escape sequence. Thus "\u015f\u00fc\u011f\u00e7\u00f6" is semantically equal to "şüğçö".

    Although those character can also be used plain, json_encode probably prefers the Unicode escape sequences to avoid character encoding issues.

    0 讨论(0)
  • 2020-12-10 18:00

    Json_encode charset solution for PHP 5.3.3

    As JSON_UNESCAPED_UNICODE is not working in PHP 5.3.3 so we have used this method and it is working.

    $data = array(
            'text' => 'Päiväkampanjat'
    );
    $json_encode = json_encode($data);
    var_dump($json_encode); // text: "P\u00e4iv\u00e4kampanjat"
    
    $unescaped_data = preg_replace_callback('/\\\\u(\w{4})/', function ($matches) {
        return html_entity_decode('&#x' . $matches[1] . ';', ENT_COMPAT, 'UTF-8');
    }, $json_encode);
    
    var_dump($unescaped); // text is unescaped -> Päiväkampanjat
    
    0 讨论(0)
  • 2020-12-10 18:04

    json_encode() does not provide any options for choosing the charset the encoding is in in versions prior to 5.4.

    0 讨论(0)
提交回复
热议问题