在php中将html元素编码为JSON

时间:2014-10-29 20:05:04

标签: javascript php html json

我试图在php中编码以下字符串,以便它可以作为JSON对象发送:

success:{'id':'success=-message', 'class':'success-message', 'inner-html':'Congratulations! You have been succesfully logged in'},

logout: {'type'='button', 'value'='logout', 'class'='logout-button'},

sessionID: {'type'='hidden', 'name'='sessionID', 'value'=1}

我如何格式化它以便使用json_encode()?

正确编码

2 个答案:

答案 0 :(得分:1)

{'success':{'id':'success=-message', 'class':'success-message', 'inner-html':'Congratulations! You have been succesfully logged in'},

'logout': {'type'='button', 'value'='logout', 'class'='logout-button'},

'sessionID': {'type'='hidden', 'name'='sessionID', 'value'=1}}

你只需要大括号(开头和结尾)就可以使它成为一个有效的JSON数组。

需要引用密钥。

答案 1 :(得分:0)

你说这是一根绳子吗?然后它看起来几乎完全json编码。只需将其包在方括号中:

echo "var myAssociativeArray = [ 
    success:{'id':'success=-message', 'class':'success-message', 'inner-html':'Congratulations! You have been succesfully logged in'},
    logout: {'type'='button', 'value'='logout', 'class'='logout-button'},
    sessionID: {'type'='hidden', 'name'='sessionID', 'value'=1}
];";

但是,好像你在PHP端创建了这个字符串(对吗?),这意味着你正在为它做json_encode工作。相反,你应该有类似的东西:

//This is a temp array just to show you how it works:
$myArr = array(
    "success" => ( object ) array(
        "id" => "success=-message",
        "class" => "success-message",
        "inner-html" => "Congratulations! You have been succesfully logged in"
    )
);

//Now you output the json version
echo json_encode( $myArr );