2013-03-05 104 views
1

我是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?

回答

5

在此處創建視圖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