Return JSON with CodeIgniter

With the ever-increasing use of Javascript and AJAX related calls, it’s would be nice to be able to quickly build endpoints that returned JSON data for our web site. Whether your rolling your own code, using jQuery or using third-party tools like KendoUI, it’s very easy to return structured data in JSON format using CodeIgniter, a PHP framework from the fine folks at EllisLab.

CodeIgniter uses a simplified Model-View-Controller pattern to help you build websites quickly without worrying about the plumbing code that seems to go into every web site you build. In a typical CI web site, each page request, calls a controller which is responsible for determining what data gets loaded and which view of the data will be presented to the requester. When loaded, the model is responsible for determining how the data is retrieved. This data is then returned to the controller which passes it on to a View. Views are responsible for taking the structured data and formatting it for presentation to the user (typically in HTML).

In this article, we’re going to look a quick and easy way to present that same data as JSON when we need it.

First, let’s take a look at our controller. We’ll use the index function which is called by default when no other function is defined in the page request URI. We’ll be passing our product ID into this function as part of the URI and CodeIgniter will use it as the $product_id parameter for this function.

load->model('Product_model', 'product');
       $data['json'] = $this->product->get($product_id);
       if (!$data['json']) show_404();

       $this->load->view('json_view', $data);
    }
  }
?>

The controller will load our product model and then call the get method, passing in the $product_id parameter. The result of this method is stored into an element in an array called $data using the key ‘json’. We then check to make sure that we actually returned a product. If not, we’ll present a ‘404 ‘“ Not Found’ error to the user’s browser. This is cleaner and safer than just sending back empty data.

db->get_where('product', array('id' => $product_id));
      return $result->row();
    }
  }
?>

Next the controller loads our very simple View passing in the entire $data array. Our view changes the output headers to application/json so the client making the request can handle it properly. In views, CodeIgniter will automatically create named variables for each of the keys in our array containing their corresponding values so our view now has access to a $json variable with our product data. We’ll simply call the PHP function json_encode() and return the results to the browser.

output->set_header('Content-Type: application/json; charset=utf-8');
  echo json_encode($json);
?>

At this point, it will send back a nice JSON object. To make a call for this data, we can simply send a request to http://example.org/product/index/17, this tells CI to use the Product controller, call the index method and pass in 17 as the first parameter, in this case, $product_id. With some CI routing magic, we can shorten this to http://example.org/product/17 by adding the following line to our applicationconfigroute.php file.

$route['product/(:any)'] = 'product/index/$1';

The result of our efforts returns a nicely formed JSON object to use as we see fit.

{
  "id"          :"17",
  "name"        :"Shoe - Black, Size 10",
  "description" :"Skecher Sport, Brown w/Black, Size 10",
  "issue_date"  :"2012-03-31",
  "show_as_new" :"No",
};

Download the sample project here: ci_json_demo.zip