Getting locale information from headers

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Getting locale information from headers

Post 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
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Getting locale information from headers

Post 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 : ?>
 
There are 10 types of people in this world, those who understand binary and those who don't
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Getting locale information from headers

Post 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 :)
Post Reply