how to get current locale in PHP

2019-07-20 06:08发布

I would like to get the current system locale of a server (say windows 7 os). This is to ensure that different language setting uses different parts of code in PHP.
However, I could not find any API that does this.
Can anyone tell me the name of the function?

标签: php locale
2条回答
干净又极端
2楼-- · 2019-07-20 06:46

Having thought more about the problem and the particular setup I have, I came up with this solution, which seems to work. Note that I don't have control over what languages I need to support: there are translation files dropped into a predefined place and system locales installed by someone else. During runtime, I need to support a particular language if corresponding translation file exists and and system locale is installed. This got me to this solution:

Use below function

function getLocale($lang)
{
    $locs = array();
    exec('locale -a', $locs);

    $locale = 'en-IN';
    foreach($locs as $l)
    {
        $regex = "/$lang\_[A-Z]{2}$/";
        if(preg_match($regex, $l) && file_exists(TRANSROOT . "/$lang.php"))
        {
            $locale = $l;
            break;
        }
    }

    return $locale;
}

I'm defaulting to en-IN if I cannot resolve a locale, because I know for certain that en-IN is installed.

查看更多
放我归山
3楼-- · 2019-07-20 06:52

Best answer above from Gags. If you want the contents of the accept-language: header from the current request, if there is one, use:

$_SERVER['HTTP_ACCEPT_LANGUAGE']
查看更多
登录 后发表回答