Getting browser language settings with PHP
Par J.Ducastel le mardi 13 septembre 2005, 20:02 - Formules - Lien permanent
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.
