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/

3 comments:

Appslure said...

Nice post
We are one of the Best service provider in Dubai like:-
Mobile app Development Company in Dubai
at http://www.appslure.online

Mobile app development company in Kuwait
at

http://www.appslure.online/mobile-app-development-company-kuwait.html


Mobile App Development Company in Abu Dhabi

at http://www.appslure.online/mobile-app-development-company-abu-dhabi-uae.html

Designpluz said...

I really appreciate this post and I like this very much. I am waiting for new post here and Please keep it up in future.. Web Development Sydney. Visit us https://www.designpluz.com.au

Home appliance repair Dubai said...

We are the responsible authorized company of Fridge repair Dubai, Refrigerator repair Dubai, Freezer repair Dubai Abu Dhabi and all over UAE. We have extensive knowledge with over 10 years of experience in this field. We repair all types of fridge brands and models that do you have. Today Call us now and get satisfaction service with our engineers.
Refrigerator repair Dubai
Refrigerator repair Abu Dhabi
Refrigerator repair