Kuldeep Dangi Kuldeep Dangi - 3 months ago 24
reST (reStructuredText) Question

How to convert an array to json in yii2

I am creating

restful apis
and I had a function to send response data in
yii1
like this

public function sendResponse($data)
{
header('Content-Type: application/json; charset=utf-8');
echo CJSON::encode($data);
exit;
}


CJSON
is not available in
Yii2
so how do i do it in
Yii2

Answer

No need to manually set header like that.

In the specific action / method you can set it like so:

use Yii;
use yii\web\Response;

...

public function actionIndex()
{
    Yii::$app->response->format = Response::FORMAT_JSON;
}

Then after that just return a simple array like that:

return ['param' => $value];

You can find this property in official docs here.

For more than one action using special ContentNegotiator filter is more flexible approach:

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        [
            'class' => ContentNegotiator::className(),
            'only' => ['index', 'view']
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
            ],
        ],
    ];
}

There are more settings, you can check it in official docs.

As for the REST, base yii\rest\Controller already has it set for json and xml:

'contentNegotiator' => [
    'class' => ContentNegotiator::className(),
    'formats' => [
        'application/json' => Response::FORMAT_JSON,
        'application/xml' => Response::FORMAT_XML,
    ],
],
Comments