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(){
header('Content-type: application/json');
echo json_encode($arr);

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);

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: