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/

1 comment:

Philips Huges said...

Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much

Personal Installment Loans
Title Car loan
Cash Advance Loan