cakephp输出数据为json

问题描述:

我是cakephp的新手,我正在尝试创建一个处理车辆的简单休息API。我想从json格式的mysql数据库中获取我的数据。cakephp输出数据为json

这是我的控制器

class VehiclesController extends AppController { 
    var $name = 'Vehicles'; 
    var $layout = 'default'; 

    function index() { 
     $this->set('vehicles', $this->Vehicle->find('all')); 
     $this->set('title_for_layout','Home'); 
    } 
} 

我怎么会出在视图中的内容以JSON?

在此处创建视图Views/Vehicles/json/index.ctp

在你看来,你应该能够使用:

<?php echo json_encode($vehicles); ?> 

要输出的JSON

然后,您可以访问此网址:/vehicles/index.json

+0

您好感谢,它的工作原理。但是,它应该作为一行文本出来 – user667430 2013-03-05 16:33:13

+1

是的,没关系 – cowls 2013-03-05 16:34:11