fredbird.org

Tous les êtres humains trébuchent un jour sur la vérité. La plupart se relèvent rapidement, secouent leurs vêtements et retournent à leurs préoccupations, comme si de rien n'était.

-- Winston Churchill (1874-1965)

fil atom des web logs

Getting browser language settings with PHP

So, you run a multilingual web site with PHP and you want to serve the reader's choice language if available. No problem, HTTP carries user's browser language settings within Accept-Language instruction, you just have to parse it. Here is a sample function :

function parseHttpAcceptLanguage($str=NULL) { // getting http instruction if not provided $str=$str?$str:$_SERVER['HTTP_ACCEPT_LANGUAGE']; // exploding accepted languages $langs=explode(',',$str); // creating output list $accepted=array(); foreach ($langs as $lang) { // parsing language preference instructions // 2_digit_code[-longer_code][;q=coefficient] ereg('([a-z]{1,2})(-([a-z0-9]+))?(;q=([0-9\.]+))?',$lang,$found); // 2 digit lang code $code=$found[1]; // lang code complement $morecode=$found[3]; // full lang code $fullcode=$morecode?$code.'-'.$morecode:$code; // coefficient $coef=sprintf('%3.1f',$found[5]?$found[5]:'1'); // for sorting by coefficient $key=$coef.'-'.$code; // adding $accepted[$key]=array('code'=>$code,'coef'=>$coef,'morecode'=>$morecode,'fullcode'=>$fullcode); } // sorting the list by coefficient desc krsort($accepted); return $accepted; }

This function will parse a given HTTP Accepted language instruction (or retrieve it from $_SERVER if not provided) and will return a sorted array. For example, it will parse fr;en-us;q=0.8 to :

[1.0-fr]=>([code]=>'fr','morecode'=>'fr',[coef]=>'1.0',[fullcode]=>'fr') ,[0.8-en]=>([code]=>'en','morecode'=>'us',[coef]=>'0.8',[fullcode]=>'en-us')

The next thing will be to find and serve the first available version amongst user's accepted languages. Easy.

Fred Bird Quintidi 25 Fructidor an 213
Commenter

Le monde est grand, le web le rétrécit. Un point de vue libertaire sur le vaste monde et nos petites vies.

Thèmes traités : politique, web & informatique, espace, Amérindiens, société, culture etc

Tous les contenus Accueil presence status jabber

Contenus similaires

Souscriptions

+ rojo + bloglines + Google reader + My Yahoo + del.icio.us add blogmarks add netvibes

Pub

Ouvaton, hébergeur coopératif Firefox Framasoft Ubuntu