Page 1 of 1

Getting locale information from headers

Posted: Sun Jan 20, 2008 5:11 pm
by alex.barylski
I could swear I've seen this done before...but I cannot find anything on Google...

I need (ideally) the locale code of the user accessing a web page so I can automatically select the locale/language...

I'm sure someone knows the magic answer... :P

Re: Getting locale information from headers

Posted: Sun Jan 20, 2008 5:53 pm
by VladSun
http://www.google.com/search?q=php+head ... __206__206

Code: Select all

 
  1 : <?php
  2 : /**
  3 :  * detect the preferred language of the user agent
  4 :  *
  5 :  * @copyright Roy Kaldung <roy@kaldung.com>
  6 :  * @license http://www.php.net/license/3_01.txt PHP license
  7 :  */
  8 : 
  9 : /**
 10 :  * split request header Accept-Language to switch
 11 :  * between english and german, default is english
 12 :  *
 13 :  * @param string $defaultlang preselected language, default en
 14 :  * @return string returns 'de' or 'en'
 15 :  */
 16 : function detectLanguage($defaultlang = 'en') 
 17 : {
 18 :     $langlist = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
 19 :     $lang = $defaultlang;
 20 :     foreach($langlist as $curLang) {
 21 :         $curLang = explode(';', $curLang);
 22 :         /* use regular expression for language detection */
 23 :         if (preg_match('/(en|de)-?.*/', $curLang[0], $reg)) {
 24 :             $lang = $reg[1];
 25 :             break;
 26 :         }
 27 :     }
 28 :     return $lang;
 29 : }
 30 : ?>
 

Re: Getting locale information from headers

Posted: Sun Jan 20, 2008 6:48 pm
by alex.barylski
Edit: I just echo'ed the results using IE7 and it spits out the language and locale...sweet...now I'll try in FF, IE6, Opera and see what happens. :P

Edit2: Doh!!! IE7 and FF output something different so now I have to parse using regex... :(

Wicked...a little involved than I was hoping for but...

That solves the language problem, what about locale? :?

Thanks for that :)