Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

{"general":{
 "round-corner":"0",
 "border-stroke":"2",
 "background-color":"#ffffff"
 }
}

I have this json string, I know that php variable names doesn't support dashes. So what to do in this case ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
448 views
Welcome To Ask or Share your Answers For Others

1 Answer

When dealing with valid json you don't need to do anything special to use the result in php as long as you don't use extract().

Admiditly it looks cleaner to let json_decode return an array here as Jay Bhatt suggests but you are also free to use a normal object as return (which is an instance of stdclass).

The properties of the returned object can be nearly anything. You just need to use the property name as a php-string instead of a hardcoded literal.

$obj->{'a sentence with spaces and umlauts ?ü? is valid here'}

<?php

$json = <<<JSON
{"general":{
 "round-corner":"0",
 "border-stroke":"2",
 "background-color ?ü??$%§":"#ffffff"
 }
}
JSON;

$obj = json_decode($json);

$keyName = "round-corner";
var_dump($obj->general->{'round-corner'});
var_dump($obj->general->$keyName);
var_dump($obj->general->{'background-color ?ü??$%§'});

Result


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...