How to add @ sign as part of object name in JSON via php

Viewed 58

I need to create JSON with php with this content

{
     "@context":"something",
     "type":"something"
}

So I created class

class doc
{
    public $context;
    public $type;
}

which gives me JSON without @ sign

{
    "context":"something",
    "type":"something"
}

If I add @ in php, I get syntax error. Is it possible that I could use @ as a part of variable name, or how can I do it?

class doc
{
    public $@context; //this is a problem
    public $type;
}

I need to have object that should be inserted into MongoDB at the end

2 Answers

Like this will do what you want

$obj = new stdClass;

$obj->{'@context'} = 'something';
$obj->type = 'somethingelse';

echo json_encode($obj);

RESULT

{"@context":"something","type":"somethingelse"}

Or if you prefer to start with an array

$arr = [];
$arr['@context'] = 'something';
$arr['type'] = 'somethingelse';
echo json_encode($arr);

RESULT

{"@context":"something","type":"somethingelse"}

You could use an associative array with your @ in your keys and encode it to json.

$array = array(
  '@context'  => 'something',
  'type'      => 'something'
);

print_r( json_encode( $array ) );

If you would like to get json out of your class variables, you could use this function:

class doc {
  public $context;
  public $type;

  public function getJson() {
    return json_encode( array(
        '@context'  => $this->context,
        'type'      => $this->type,
    ) );
  }
}


$doc = new doc;
$doc->context = 'something';
$doc->type = 'something';

print_r( $doc->getJson() );

Both prints

{
  "@context":"something",
  "type":"something"
}
Related