28 Feb 2012 danstowell   » (Journeyer)

Simple PHP content negotiation for HTML vs TTL

I'm writing a simple PHP web application. Normally it outputs HTML, but for linked data purposes I'd also like to be able to output RDF in Turtle format, from the SAME URL. This is achieved using something called content negotiation.

Often you can configure your webserver to do the right thing, but in this case I don't have access to the Apache config. I haven't been able to find a simple bit of PHP code for the content negotiation (or at least, not one that behaves correctly) so here's my attempt.

Note that this is NOT a complete flexible content negotiation. It only handles the case where I can output HTML or TTL and nothing else:

  // Content-negotiation, here only choosing if we can output HTML or TTL
preg_match_all('|([\w+*]+/[\w+*]+)(;q=([\d.]+))?|', $_SERVER['HTTP_ACCEPT'], $acceptables, PREG_SET_ORDER);
$accept_html = 0;
$accept_ttl  = 0;
foreach($acceptables as $accarray){
        $acclev = isset($accarray[3]) ? $accarray[3] : 1;
        switch($accarray[1]){
                case 'text/html':
                case 'html/xml':
                        $accept_html = max($accept_html, $acclev);
                        break;
                case 'text/rdf+n3':
                case 'application/turtle':
                case 'application/rdf+n3':
                case 'text/turtle':
                        $accept_ttl  = max($accept_ttl , $acclev);
                        break;
                case '*/*':
                        $accept_html = max($accept_html, $acclev);
                        $accept_ttl  = max($accept_ttl , $acclev);
                        break;
        }
}

$negotiatesttl = $accept_ttl > $accept_html; // only output ttl if it's higher-requested than html

if($negotiatesttl){
    // output ttl
}else{
    // output html
}

Here's hoping it works.

Syndicated 2012-02-28 10:26:44 (Updated 2012-02-28 10:29:53) from Dan Stowell

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!