Tuesday, July 3, 2012

Handle JSON Response in Yii

Convert array to json data
convert array data to json using json_encode() function use the below example, $this->layout=false makes yii to stop rendering layout for this action.

public function actionJsonTest(){
$this->layout=false;
$arr=array('Fruits'=>array('apples','orange'),'Vegetables'=>array('beans','carrot'));
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end();
}


Convert model data to json 
convert your existing model data to json
  header('Content-type: application/json');
  $post = Post::model()->findByPK((int)$id);
  echo CJSON::encode($post);
  Yii::app()->end();


Convert model data with relations to json 
use this behaviour Converts Model Attributes and its Relations to a JSON  http://www.yiiframework.com/extension/ejsonbehavior/

No comments: