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

emir :

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

RiggsFolly :

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"}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=26198&siteId=1