This is part 3 of my article about writing a restful service server. If you haven’t already, you might like to read part 1 (covering the core library and grabbing the information we need from the incoming request) and part 2 (covering the service handler itself) before reading this section. This part covers the Response object that I used to return the data to the user in the correct format.
XML Response Object
Exactly what output you want from your service completely depends on the specification and what you are actually trying to do. I wrote a really simple response wrapper that responds with an outline tag containing a status, and then either the content or some error details. Here’s my response class:
class Response {
public function output() {
header('Content-type: text/xml');
echo '';
echo "\n";
echo '';
echo "\n";
foreach($this as $prop_key => $prop_value) {
if(!is_array($prop_value)) {
echo '<'.$prop_key.'>';
echo $prop_value;
echo ''.$prop_key.'>';
echo "\n";
} else {
echo '<'.$prop_key.'>';
echo "\n";
foreach($prop_value as $array_key => $array_value) {
echo '<'.$array_key.'>';
echo $array_value;
echo ''.$array_key.'>';
echo "\n";
}
echo ''.$prop_key.'>';
echo "\n";
}
}
echo " \n";
}
}
This could be more elegant and thorough, but its kind of an outline of what I did. Firstly set the content header, then the main tag. Then it loops through all the properties set against the response object and just writes them out as XML. Its very limited but at least its short enough to read easily! There is also an error response that gets called and returns the error type and message, setting the response status to “error” rather than “ok”.
REST Service in PHP
So there you have the ingredients for a REST server in PHP. I’m sure this isn’t the only way to solve this problem, but this is how I did it and I hope it helps someone. If you’ve got any questions, feel free to comment below – and if you do use this for a project, I’d love to hear from you :)