News Archive
PhpRiot Newsletter
Your Email Address:

More information

Building a RESTful PHP Server: Output Handlers

Note: This article was originally published at Planet PHP on 1 February 2012.
Planet PHP

This is the third installment in my series about writing a RESTful web service in PHP. It is probably the last one but there are a few other things I'd like to cover such as error handling, so I might keep adding to it, especially if I get any particular requests or interesting questions in the comments. So far we've covered parsing requests to determine exactly what the user is asking for, and also looked at routing to a controller to obtain the data or perform the action required. This post gives examples of how to return the data to the client in a good way.

Output Handlers Instead of Views

We'll have as many output handlers as we have supported output formats. The joy of having all the controllers return the data to index.php is that we can then add common output handling to all the data. In our example system, we can remove that ugly print_r from index.php and instead detect which output format is needed and load the relevant view. My code looks like this:

$view_name = ucfirst($request-format) . 'View'; if(class_exists($view_name)) { $view = new $view_name(); $view-render($result); }

The most simple example is a JsonView which looks like this:

A class JsonView extends ApiView { public function render($content) { header('Content-Type: application/json; charset=utf8'); echo json_encode($content); return true; } }

As you can see here, it's pretty simple! We send the Content-Type header first to let the consumer know what's in the response, then we just encode the JSON and echo it out.
To support other formats, you might loop over your array (remember it might be nested - things usually get recursive at this point for something like an XML format) and transform it into the new format. Between two PHP systems, it might be simpler to support serialised PHP as a format as it is a little more verbose than the JSON.

I also like to support html as an output format - for example the API does this; just go to with your browser and it will realise you're a web browser and return you the html version. is open source and since I wrote it

Truncated by Planet PHP, read more at the original (another 2412 bytes)