Welcome Guest, Not a member yet? Register   Sign In
Outputting xml/json/html dependent on requirement
#1

[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.
#2

[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
#3

[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!




Theme © iAndrew 2016 - Forum software by © MyBB