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?

1 Answer 1

5

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

 echo $obj->data[0]->{'$id'}; // 1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.