12

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

3 Answers 3

24

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,
    ],
],
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks arogachev for great information. although my question was just on how to json encode in yii2 , you added a great info on settings headers Thanks a lot
3

::find()->asArray()->all(); wish help.

Comments

3

You could use Json class in yii2 from

yii\helpers\Json;

It contain methods such as :

Json::encode();
Json::decode();

These methods directly converts yii2 activerecord objects into json array.

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.