Gettext will always use system default locale

后端 未结 7 707
孤城傲影
孤城傲影 2020-12-30 09:30

I need to localise a Windows-only PHP web application and I\'m evaluating the gettext extension but I\'m having the hardest time trying to make it work in my Windows 7 devel

7条回答
  •  庸人自扰
    2020-12-30 09:55

    First problem: setlocale()

    To make this work, you need to set a valid locale. On windows, setlocale() won't work as expected. You need to set an environment variable, like this:

    // putenv("LANG=$lang");  <- WRONG!
    putenv('LC_ALL='.$locale);
    

    Second problem: locale names.

    Windows locale names are different from Linux. Try with 'ita', 'eng', 'deu', 'ger', 'esp'. You can get a complete list here: http://www.microsoft.com/resources/msdn/goglobal/default.mspx

    Example:

    //putenv("LANG=esp");  <- WRONG!
    putenv('LC_ALL=esp');
    

    Third problem, the big one: gettext extension on windows is not thread safe. Each time you change language, the change is process wide. If you run php as fast-cgi you're ok. If you run php as apache module (for example) it's a total mess because language changes for every php instance. The problem is that gettext() relies on locale setting. This setting is process wide on windows PHP. You cannot change locale for a PHP thread but only for PHP process.

    Said this, here is some working code:

    // $MAINPATH is your document root
    
    $locales=array(
      'it'=>'ita',
      'en'=>'eng',
      'de'=>'deu',
      'fr'=>'fra',
      'es'=>'esp',
      'ru'=>'rus'
    );
    
    $locale = $locales[$lang];
    $res=putenv('LC_ALL='.$locale);
    $rres=bindtextdomain('default', $MAINPATH.'locale');
    $dres=textdomain('default');
    

    locale directory structure must be the following:

    deu
      LC_MESSAGES
        default.mo
    esp
      LC_MESSAGES
        default.mo
    fra
      LC_MESSAGES
        default.mo
    ita
      LC_MESSAGES
        default.mo
    rus
      LC_MESSAGES
        default.mo
    

提交回复
热议问题