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
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.
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,
],
],
::find()->asArray()->all(); wish help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With