Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set content-type to json in symfony

I am using symfony 1.4, to create my project with propel as ORM. i want to get the response in JSON format, when i call a url. I have set the headers to "application/json" but it is not working, i am getting the response back in HTML format..which i am not able to decode. How can we set content-type in symfony?? example code: Action-

 public function executeIndex(sfWebRequest $request)
 {
     $data_array=array("name" => "harry", "mobile" => "9876543210");
     $data_json=json_encode($data_array);
     $this->output=$data_json;  
 }

View-

<?php
  header('Content-type: application/json');
  echo $output;
?>
like image 621
Harish Kurup Avatar asked Oct 26 '10 06:10

Harish Kurup


4 Answers

Oh ! As an alternative, I'd just say I have been using the routing system, which provides a pretty neat way to get it done:

-> In your routing.yml

json_test:
  url: /test
  class: sfRequestRoute
  param: { module: test, action: index, sf_format: json }

Then, the frameworks will automatically pick up you view index.json.php, which you have to create. As mentioned above, you can generate the content in the action with json_encode, though there are arguments to put it in the view.

Now... Ok, if you are interested in picking some more about this, have a look at the "Practical symfony" tutorial: Day 15: Web Services There's some good stuff down there !

like image 114
mika Avatar answered Nov 10 '22 06:11

mika


You can also define this in the view.yml (apps/{app_name}/modules/{module_name}/config/view.yml) file for the module.

indexSuccess:
  has_layout: false
  http_metas:
    content-type: application/json
like image 28
Dan Morphis Avatar answered Nov 10 '22 06:11

Dan Morphis


ok i got where i was going wrong..yhe code should have been.. Action-

public function executeIndex(sfWebRequest $request)
{
 $this->getResponse()->setContentType('application/json');
 $data_array=array("name" => "harry", "mobile" => "9876543210");
 $data_json=json_encode($data_array);
 return $this->renderText($data_json); 
}

this code has worked for me, please post if any better solution you have got..

like image 20
Harish Kurup Avatar answered Nov 10 '22 04:11

Harish Kurup


In a REST style, just add .format to the URI, create the relative template and Symfony Routing system does the rest of the work for us.

like image 1
pagaio Avatar answered Nov 10 '22 05:11

pagaio