PHP Localisation

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
Darkzaelus
Forum Commoner
Posts: 94
Joined: Tue Sep 09, 2008 7:02 am

PHP Localisation

Post by Darkzaelus »

Is there anything in the HTTP header that I can use to pick languages for php for a multilingual website?

Cheers,

Darkzaelus
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: PHP Localisation

Post by VladSun »

I use this:

Code: Select all

$languageFileMapping = Array(
    'en' => 'english',
    'bg' => 'bulgarian',
    'ru' => 'russian',
);
 
$defaultLanguage = 'en';
 
if (empty($_SESSION['language']))
{
    $parsedLanguages = explode(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
    foreach ($parsedLanguages as $parsedLanguage)
    {
        $language = substr($parsedLanguage, 0, 2);
        if (array_key_exists($language, $languageFileMapping))
        {
            $_SESSION['language'] = $language;
            break;          
        }
    }
}
 
if (empty($_SESSION['language']))
    $_SESSION['language'] = $defaultLanguage;
There are 10 types of people in this world, those who understand binary and those who don't
Darkzaelus
Forum Commoner
Posts: 94
Joined: Tue Sep 09, 2008 7:02 am

Re: PHP Localisation

Post by Darkzaelus »

Wonderful! Will keep this in mind when i start localising my code.

Cheers! Darkzaelus
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: PHP Localisation

Post by VladSun »

You're welcome :)
A little fix to apply:
change the IF line to:

Code: Select all

if (!empty($language) && array_key_exists($language, $languageFileMapping))
to avoid PHP warnings
There are 10 types of people in this world, those who understand binary and those who don't
Darkzaelus
Forum Commoner
Posts: 94
Joined: Tue Sep 09, 2008 7:02 am

Re: PHP Localisation

Post by Darkzaelus »

Thanks once again!
Post Reply