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;
?>
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 !
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
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..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With