cakephp输出数据为json

use*_*430 1 json cakephp

我是cakephp的新手,我正在尝试创建一个简单的休息api来处理车辆.我想以json格式从mysql数据库中获取我的数据.

这是我的控制器

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何在视图中以json的形式输出内容?

cow*_*wls 5

在这里创建一个视图Views/Vehicles/json/index.ctp.

在您的视图中,您应该能够使用:

<?php echo json_encode($vehicles); ?>
Run Code Online (Sandbox Code Playgroud)

输出JSON

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