Home » Php » php json decode with variables that contains dashes

php json decode with variables that contains dashes

Posted by: admin July 12, 2020 Leave a comment

Questions:
{"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 ?

How to&Answers:

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

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