Other things on this site...

MCLD
music
Evolutionary sound
Listen to Flat Four Internet Radio
Learn about
The Molecules of HIV
MCLD
software
Make Oddmusic!
Make oddmusic!

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.

| technology | Permalink

social