NagiosEnterprises/nagiosvshell — pull request #3 by chrislaskey (2014-02-05 18:18:46+00:00)
Title: Automated XML and JSON output for API controllers

To help with the API process here's some code to automate XML and JSON output. Now in each controller all we have to do is assemble the requested data in a PHP array then call the output method.

In other words, right now inside a controller we do:

$data = 'some multi dimensional array of data pulled from the model and processed in the controller';
$this->load->view('template-name', $data);

Now we can do:

$data = ' same data process ...';
$this->output($data);

And that's it. The new output function accepts a PHP array, $data, and outputs either XML or JSON with proper HEADER values depending on the GET value "format". If no GET values are passed, it defaults to JSON, which is the easiest format to work with in AngularJS.

This should simplify writing API controllers as they don't need to worry about return format and the same code can be used for all return types. API callers can use APIs like:

/vshell2/api/details/host/localhost

And if they want XML or another non default format they can append the get variables to any API URI:

/vshell2/api/details/host/localhost?format=xml

And we don't have to catch it, or worry about it in the specific controller.

I'm assuming we want to support RHEL 5.X, which uses PHP 5.1.6. Since built-in JSON support wasn't added until PHP 5.2.X, I imported the official JSON library for PHP < 5.2 from PHP PEAR as a CodeIgniter library. I also created a basic Array to XML helper function using PHP's SimpleXML library.