I’m new to cakephp and json. I’ve recently build a rest service with cakephp. Everything seems to be working. When i query a link using this code beneath that is stored in a separate file:
<?php
$request = 'http://localhost/tut_blog/posts/';
$response = file_get_contents($request);
echo $response;
?>
I get the return in html because i programmed my view file that way. Her is my view file: index.ctp
<h2>View all posts</h2>
<table>
<tr>
<th>Title</th>
<th>Body</th>
</tr>
<?php foreach($posts as $post):?> // met de functie foreach wordt er hier geloopt door de variable $posts die we eerder in de controller hadden aangemaakt en die alle waarden bezit van de query die we eerder hadden opgesteld.
<tr>
<td><?php echo $post['Post']['title'];?></td> // de $posts array bevat 2 sleutels nr 1 = naam van de model, nr 2 = de naam van de veld in je tabel.
<td><?php echo $post['Post']['body'];?></td>
</tr>
<?php endforeach; ?>
</table>
I want to know how i can get this same data but then in JSON output.
Here’s my controller file as well:
<?php
class PostsController extends AppController{
var $name = 'Posts';
var $components = array('RequestHandler');
function hello_world(){
}
function index(){
$this->set('posts',$this->Post->find('all'));
}
function view($id = NULL){
$this->set('post',$this->Post->read(NULL, $id));
}
}
?>
Assuming you want to keep your html version, and want to also supply a json version, then there are a couple of things you need to do.
1) Make sure extensions are being passed so that you can do
http://localhost/tut_blog/posts/index.json. There’s info at http://book.cakephp.org/view/1239/The-Simple-Setup (for *.xml, same idea for *.json), but in essence you add the following toapp/config/routes.php:2) Create a view that returns json. For your case you could have a view at
app/views/posts/json/index.ctpsimilar to the following…In the view above I’ve left plenty of places for you to insert debug stuff, but you could write it a lot more compact once you’re happy (
<?php echo $this->Js->object($posts); ?>).3) Make sure you have a json layout (
app/views/layouts/json/default.ctp):That’s the simplest layout you can do, although for one of my clients we’ve put a little more intelligence into it so that we can have a standard method of returning errors:
In this way, if the requested url ends with .json you’ll get the view above, otherwise the default view and layout will be used (usually html).
4) You may need to add the Js helper to your controller, or better still app_controller.php to enable it for all views. There’s the possibility you won’t need to add it as CakePHP might auto include it based on the layout, but we’ve had the Js helper in app_controller.php since before adding json output, so I can’t tell you for sure.