1

I have a json like the following

{"root":{
                "version":"1",
                "lastAlarmID":"123",
                "proUser":"1",
                "password":"asd123##",
                "syncDate":"22-12-2014",
                "hello.world":"something"
}
}

After json_decode(), I can get all the values except that of the last one hello.world, since it contain a dot.

$obj->root->hello.world doesn't work. I got solutions for doing it in Javascript but I want a solution in php.

Mike
  • 22,114
  • 13
  • 72
  • 84
Aneeez
  • 1,350
  • 3
  • 12
  • 19

4 Answers4

3

$obj->root->{'hello.world'} will work.

ps: $obj->root->{hello.world} might not work.

b.t.w: Why not use Array? json_decode($json, true) will return Array. Then $a['root']['hello.world'] will always work.

Clarence
  • 721
  • 1
  • 5
  • 9
1

This is working

echo $test->root->{'hello.world'};

Check example

<?php

$Data='{"root":{
                "version":"1",
                "lastAlarmID":"123",
                "proUser":"1",
                "password":"asd123##",
                "syncDate":"22-12-2014",
                "hello.world":"something"}
}';
$test=json_decode($Data);
print_r($test);
echo $test->root->{'hello.world'};
?>

Output

something
Saty
  • 22,213
  • 7
  • 30
  • 49
1

You have two options here:

First option: convert the object to an array, and either access the properties that way, or convert the name to a safe one:

<?php
$array = (array) $obj;
// access the value here
$value = $array['hello.world'];

// assign a safe refernce
$array[hello_world] = &$array['hello.world'];

Second option: use quotes and brakets:

<?php
$value = $obj->root->{'hello.world'};
Bryan Agee
  • 4,636
  • 3
  • 25
  • 41
-1

You can use variable variables (http://php.net/manual/en/language.variables.variable.php):

$a = 'hello.world';
$obj->root->$a;
rap-2-h
  • 26,857
  • 31
  • 150
  • 246