本記事では、JSON出力を行うサンプルプログラムを解説しています。
JSONを利用する機会は多いと思いますので、ぜひ、参考にして下さい。
サンプルプログラムでは、Usersテーブルの検索条件に該当するレコードを、JSON形式で返却する例となっています。
コントローラーの作成
Users テーブルの name に曖昧検索に一致するレコードを検索し、JSONに変換して返却します。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | SimpleJsonController.php     public function conv()     {         $name = $this->request->query('name');         $this->viewBuilder()->autoLayout(false);         $this->autoRender = false;         $this->response->charset('UTF-8');         $this->response->type('json');         $this->loadModel('Users');         $res = $this->Users->find('all', ['conditions' => ['name like' => '%'.$name.'%']]);         $this->response->body(json_encode($res));     } | 
動作確認
下記のURLにアクセスすると、生成した画面が表示されます。
http://ドメイン名/app/Siimple/conv
データベースの検索結果ではなく、配列をJSON形式で返却する例です。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | SimpleJsonController.php     public function conv()     {         $this->viewBuilder()->autoLayout(false);         $this->autoRender = false;         $this->response->charset('UTF-8');         $this->response->type('json');         $dummy = [                     'id' => '1',                     'name' => 'hogehoge',                     'notes' => array(                         ['id' => 1, 'note' => 'メモ1です'],                         ['id' => 2, 'note' => 'メモ2です'],                         ['id' => 3, 'note' => 'メモ3です']                  )];         $this->response->body(json_encode($dummy));     } | 
 
  
  
  
  
 
 
         
         
         
         
         
        
