Search code examples
phplocalegettext

gettext and locale


I can't seem to get this right nor understand it.

I have this code:

putenv('LC_ALL=eng_US.UTF-8');
var_dump(setlocale(LC_ALL, 'eng_US.UTF-8', 'eng_US'));

The output on Windows

string 'English_United States.1252' (length=26)

The output on Linux

bool(false)

Linux works with en_US, but not Windows. Windows looks into the folder eng_US and Linux en_US.

Did anyone find a solution to this? Or is there a way to put a custom string that will be taken into account regardless of the OS?

(I must add, I'm using WAMP on Windows-7 and the Linux machine is a CentOS with nginx + php-fpm)


Solution

  • locale names are platform dependent.

    On most unix systems you want <two letter language code>_<two letter country code>[.<optional encoding>]. You can use the command line locale -a to list valid locale names.

    Proper Windows locales use the same X_X[.X] scheme except that they use full names for languages and countries, and they use code page numbers instead of encoding names: English_United States.1252. Windows also seems to have some heuristics for figuring out other strings, though it doesn't seem to go as far as working for Unix style locale names. Also Windows does not support UTF-8 as a locale encoding whether you specify it with the name 'UTF-8' or using the codepage number '65001'.

    As you've found out locale names for Windows and for other platforms are different. You can't use the same string for all platforms. Instead you'll have to write code that uses the correct string for the current platform.

    if Linux
        return "en_US.UTF-8"
    if Windows
        return "English_United States.1252"