PHP Rest Server (part 3 of 3)

Edit: I have a newer series of articles on this topic. You can start reading here :)

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 '';
                echo "\n";
            } else {
                echo '<'.$prop_key.'>';
                echo "\n";
                foreach($prop_value as $array_key => $array_value) {
                    echo '<'.$array_key.'>';
                    echo $array_value;
                    echo '';
                    echo "\n";
                echo '';
                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 :)

8 thoughts on “PHP Rest Server (part 3 of 3)

  1. Olá, hoje no blog da Lorna Jane saiu a terceira e ultima parte de como fazer um REST Server em PHP. Aqui você pode ver o primeiro, segundo e terceiro artigo.
    Basicamente ele tem o mesmo comportamento do que um SOAP service. Ótimo guia para quem vem …

  2. please fix the example – escape output!!! – cant say how many time’s i’ve seen commercial code with bugs like that..

    JSON is now more commonly used to do this stuff.. XML is used mainly for compatibility with REALLY OLD systems now.. ;)

    • Presumably, there’s no escaping / filtering because it’s concentrating on the ReST side of the service, not on the many other best-practice sides of PHP.

      XML is still quite widely used, and it’s potentially a better choice than JSON when (eg) exposing APIs at the edge of your application (ie for third-parties to interact with) because it’s easier to represent complex types with it and the parsers are more mature (eg large documents can be parsed as a stream using off-the-shelf parsers). Plus, it’s arguably more human-readable than JSON.

      Don’t get me wrong, JSON definitely has it’s place, but probably so does XML.

  3. Andrew: As magicmonkey says, I ripped out all the extra bits and bobs to make these examples more readable. I think the point about using JSON as a transport is a very valid one though, many languages now have built-in support for working with JSON objects so this would be a valid choice.

    magicmonkey: hey there, thanks for dropping in, you are exactly right about my having removed code to try to keep the examples to the point :)

  4. so where is the example code?

    in part one you show this code…

    $service = new Rest_Service();
    // instantiate the main functional class and pass to service
    $library = new Library();
    // create a response object and pass to service
    $response = new Response();

    …yet nowhere to you show the $Rest_Service() class definition.


    what good is this article without a working source example that we can play with?

    thanks, but more info would have been more helpful.

    – mark

    • thxs for the reply…but i still think a zip file with a working example would be far more helpful the a fragmented article is.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.