Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php json decode with variables that contains dashes

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

like image 689
Xsmael Avatar asked Jun 25 '14 13:06

Xsmael


People also ask

What is json_encode and json_decode in PHP?

JSON is based on two basic structures namely Objects and Arrays. Parsing JSON data in PHP: There are built-in functions in PHP for both encoding and decoding JSON data. These functions are json_encode() and json_decode(). These functions works only with UTF-8 encoded string.

What is Echo json_encode in PHP?

The json_encode() function is used to encode a value to JSON format.

What is json_decode PHP?

The json_decode() function is used to decode or convert a JSON object to a PHP object.

What does json_decode return?

The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.


1 Answers

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

like image 113
Rangad Avatar answered Sep 27 '22 18:09

Rangad