CodeIgniter Forums
Outputting xml/json/html dependent on requirement - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Outputting xml/json/html dependent on requirement (/showthread.php?tid=18941)



Outputting xml/json/html dependent on requirement - El Forum - 05-22-2009

[eluser]Unknown[/eluser]
I'm just starting to get the hang of this MVC thing but I'm not quite sure how to handle this problem:

I currently have a fairly solid Upload controller which activates the upload_complete view upon a successful upload. What I would like is for this view to output either XML, JSON or just regular HTML dependent on the request.

For starters, I'm not sure how to pass that information through to the controller/view. For example, when using the Twitter API you just change the feed extension as you so desire: feed.xml / feed.json / feed.atom ... How can I have something similar with CodeIgniter?

It doesn't have to be similar...

One thought I had was to create two functions within my Upload class: "do_upload_jsonoutput" and "do_upload_xmloutput" - and then you can submit to either: "url/path/upload/do_upload_jsonoutput" ... but this seems a bit messy - there must be a better way!

Any help is appreciated.


Outputting xml/json/html dependent on requirement - El Forum - 05-22-2009

[eluser]Jamie Rumbelow[/eluser]
Hey James,

There are loads of ways of going about this - you can take the Rails style of using the extension to provide the output type (feed.xml feed.json etc.). You could use an individual method for each type, you can pass a parameter through specifing it. It's really up to your style and personal preference.

I like to go with the last on - say if you have a 'finished' method in your controller, you can do something like this:

Code:
function finished($format) {
  $response = 'Done uploading!';

  switch ($format) {
    case 'json': json_encode($response); break;
    case 'xml': echo $response; break;
    case 'html': $this->load->view('success'); break;
  }
}

This will make your URLs look like: controller/action/format.

Hope that helps!

Jamie


Outputting xml/json/html dependent on requirement - El Forum - 05-22-2009

[eluser]Unknown[/eluser]
@Jamie, thanks mate, I've taken your suggestion and it works perfectly. I wasn't aware that function parameters were definable through the URL; I should've guessed! CodeIgniter is awesome! Big Grin

Thanks again!