24 September 2010

This tutorial shows you how you can generate JSON from SQL data that comes from model. Converting query to JSON is really simple in PHP and even simpler in CodeIgniter.

You can generate JSON data as string or as seperate file. We convert it to seperate file/url because that is a lot of easyer and it basically makes no difference.

Model:

We need a basic model that gets some data, any data from SQL database is fine actually. It should look something like:
Source code viewer
  1. <?php
  2. class My_model extends Model {
  3. function My_model() {
  4. parent::Model();
  5. $this->load->database();
  6. }
  7. function get_people() {
  8. static $query;
  9. $this->db->select('id, name');
  10. $query = $this->db->get('people');
  11. #If you don't want to use acrtive record then you can write your own querys aswell
  12. #example: $query = $this->db->query('SELECT id, name FROM people');
  13.  
  14. if($query->num_rows() > 0) return $query->result();
  15. else return FALSE;
  16. }
  17.  
  18. }
  19.  
  20. /* End of file my_model.php */
  21. /* Location: ./system/application/models/my_model.php */
Programming Language: PHP

Query to JSON Controller:

I have a json controller. That generates some JSON code to a file/url.
Source code viewer
  1. <?php
  2. class Json extends Controller {
  3. function __construct() { #<-PHP5 - __construct(); PHP4 - class name()
  4. parent::Controller();
  5. $this->load->model('my_model');
  6. }
  7. function index(){
  8. header('Content-type: application/json');
  9. echo json_encode($this->my_model->get_people());
  10. }
  11. }
  12.  
  13. /* End of file json.php */
  14. /* Location: ./system/application/controllers/json.php */
Programming Language: PHP
Now you know how to convert query to JSON in CodeIgniter.