代码之家  ›  专栏  ›  技术社区  ›  hollsk

编码问题-一种格式到另一种格式

  •  5
  • hollsk  · 技术社区  · 14 年前

    \u00e4
    

    对于一个带元音变调的小“a”(没有我认为应该在那里的双引号)*。当然,这会在我的HTML中呈现为纯文本。

    *下面是一个json示例:

    ({"content":{"pagelet_tab_content":"<div class=\"post_user\">Latest post by <span>D\u00e4vid<\/span><\/div>\n})
    
    2 回复  |  直到 14 年前
        1
  •  6
  •   Pascal MARTIN    14 年前

    考虑到\u00e4是Unicode字符的Javascript表示,可以使用 json_decode()

    有效的JSON字符串为:

    $json = '"\u00e4"';
    

    还有这个:

    header('Content-type: text/html; charset=UTF-8');
    $php = json_decode($json);
    var_dump($php);
    

    将为您提供正确的输出:

    string 'ä' (length=2)
    

    (只有一个字符,但有两个字节长)


    不过,感觉还是有点黑^^
    它可能不会工作得太好,这取决于作为输入的字符串的类型。。。

    [编辑] 我刚刚看到您的评论,您似乎表示您获得了JSON作为输入?如果是的话, json解码() 可能真的是这项工作的合适工具;-)

        2
  •  5
  •   Gkiokan    8 年前

    您可以为json_encode/json_decode函数提供额外的参数来“强制”它使用utf-8。我正在为此构建一个简单的类,并使用静态方法来获得结果。

    关键是旗帜 JSON\u UNESCAPED\u UNICODE . 像这样使用:

    /*
        Data Class
        * * * * * * *
        Encode and Decode Your String / Object / Array with utf-8 force.
    */
    class Data {
    
        // Encode
        // @param $a  Array Element to decode in JSON
        public static function encode($a=[]){
            $json = json_encode($a, JSON_UNESCAPED_UNICODE);
            return $json;
        }
    
        // Decode
        // @param $a  JSON String
        // @param $t  Type of return (false = Array, true = Object)
        public static function decode($a='', $t=false){
            $obj = json_decode($a, $t, 512, JSON_UNESCAPED_UNICODE);
            return $obj;
        }
    }
    

    用法

    // Get your JSON String
    $some_json_string = file_get_contents(YOUR_URL);
    
    // Decode as wish
    $json_as_array    = Data::decode($some_json_string);
    $json_as_object   = Data::decode($some_json_string, true);
    
    // Debug / use your Content 
    echo "<pre>";
    print_r($json_as_array);
    print_r($json_as_object);
    echo "</pre>";