Search code examples
jsonsymfony1content-type

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

Solution

  • 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..