Show Page Data In JSON Format In CodeIgniter

Sometimes we need to load the data of page in json format when any API is requested for only data rendered on the page or the dynamic data that is passed on the view from controller.

Suppose you need data of the home page of your site in json format. To run the specific script , I have taken a query parameter format , which is when passes in URL then only you get json in output of the page otherwise only html is rendered in output of browser as usually it appears.

E.g – https://********/home?format=json

It is important to know that in CodeIgniter view is prepared in the view function of Loader  class of core that is present in the system/core/. So for adding any extra functionality in the view we have to extend the view function of the loader class.

How To Set  JSON In Output:

Create a custom class MY_Loader in application/core . All extended classes of core must be present under the core folder of application and class name should be same as core class with prefix set in config.php. Like I have set the prefix for extended classes as  ‘MY_’ ( $config[‘subclass_prefix’] = ‘MY’ ). You can check in config.php of your application.

How To Show Output:

After all  the views get loaded of the home page , output array has been set  with all parameters of the  page e.g. home.

Now what we have to do is show output json on the web using display_override hook of CI controller. You can use your own method to display  on web or send the json in requested API.

To show json formatted output on the web , Create a hook on display override in hooks.php as –

Then create a  Class Formatting under the folder application/hooks/ . On which simply echo output json using get_ouput method of OUTPUT class.

Check our blog on CodeIgniter Security enhancement.

Please follow and like us:
20

Leave a Reply