Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a JSON value with a php $Key value

Tags:

json

php

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?

like image 924
topher Avatar asked Feb 14 '26 01:02

topher


1 Answers

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

 echo $obj->data[0]->{'$id'}; // 1
like image 80
topher Avatar answered Feb 16 '26 14:02

topher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!