{"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 ?
{"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 ?
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 äü??$%§'});
You can use an array format like this. Hyphened keys will work.
<?php
$json = '{"general":{
"round-corner":"0",
"border-stroke":"2",
"background-color":"#ffffff"
}
}';
$array = json_decode($json, true);
echo $array['general']['border-stroke']; // prints 2
?>
Here's a demo