PHP decoding and encoding json with unicode characters

前端 未结 8 967
野性不改
野性不改 2020-11-27 17:46

I have some json I need to decode, alter and then encode without messing up any characters.

If I have a unicode character in a json string it will not decode. I\'m n

相关标签:
8条回答
  • 2020-11-27 18:35

    A hacky way of doing JSON_UNESCAPED_UNICODE in PHP 5.3. Really disappointed by PHP json support. Maybe this will help someone else.

    $array = some_json();
    // Encode all string children in the array to html entities.
    array_walk_recursive($array, function(&$item, $key) {
        if(is_string($item)) {
            $item = htmlentities($item);
        }
    });
    $json = json_encode($array);
    
    // Decode the html entities and end up with unicode again.
    $json = html_entity_decode($rson);
    
    0 讨论(0)
  • 2020-11-27 18:36

    try setting the utf-8 encoding in your page:

    header('content-type:text/html;charset=utf-8');
    

    this works for me:

    $arr = array('tag' => 'Odómetro');
    $encoded = json_encode($arr);
    $decoded = json_decode($encoded);
    echo $decoded->{'tag'};
    
    0 讨论(0)
提交回复
热议问题