3

While answering Get JSON object from URL Difficulties, I noticed one of the JSON names was "$id":

{ "data" : [
    {
        "$id": "1",
        "SearchKey": "Alnwick |Alnwick",
        ...

This caused the following php code to throw different errors:

$json = ... //json above
$obj = json_decode($json);
echo property_exists($obj->data[0], '$id'); // prints true
echo $obj->data[0]->$id; // PHP Fatal Error: Cannot access empty property ...
echo $obj->data[0]->id; // PHP Notice: Undefined property stdClass::$id ...
echo $obj->data[0]->'$id'; // PHP Parse Error: syntax error, unexpected ''$id'' (T_CONSTANT_ENCAPSED_STRING) ...

Assuming the json is decoded as objects not arrays, how can I access the "$id" field?

Community
  • 1
  • 1
topher
  • 14,465
  • 7
  • 54
  • 69

1 Answers1

5

Accessing the variable via {'invalid-parameter-name'} works:

 echo $obj->data[0]->{'$id'}; // 1
topher
  • 14,465
  • 7
  • 54
  • 69