4

I have a json object that looks like this:

{#119130 ▼
  +"@id": "1EBEF5DA"
  +"@name": "The"
  +"@renewal": "xxxxx"
  +"@languages": "Eng"
}

How do I access a the JSON data in php when the identifier starts with an @ symbol?

For example trying to access it using $var->@id results in an error:

Parse error: syntax error, unexpected '@', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

I tried $var->id but it results in an Undefined Property.

kevinabraham
  • 1,378
  • 4
  • 28
  • 55
  • You can try accessing it via `$var['@id']`. If this works I will add it as an answer for you. – cramopy Aug 12 '17 at 08:54
  • 1
    why would the json property be prefixed with an `@`? It's not invalid, but what's the point? – Gordon Aug 12 '17 at 09:11
  • @Gordon not sure why the clients developers did it this way. This is just the response I get from the clients server and was supposed to process it. – kevinabraham Aug 12 '17 at 09:40

3 Answers3

6

Use this:

$a = '{"@id":"123","@idx":"2232"}';
$b = json_decode($a);
print_r($b);
echo $b->{'@id'};
d_void
  • 123
  • 10
4

Keep element name in one variable like $test and use $var->$test to get value like this

 <?php
    $arr = json_decode(json_encode(["@id"=> "1EBEF5DA"]));
    $obj = '@id';
    print_r($arr->$obj);
 ?>

Demo : https://eval.in/844662

Or another way is print_r($arr->{'@id'});

Demo : https://eval.in/844662

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
3

Try it like this:

$idFieldName = '@id';
$var->$idFieldName;
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
Drusantia
  • 327
  • 1
  • 8