how to get current locale in PHP

六月ゝ 毕业季﹏ 提交于 2020-01-15 06:19:12

问题


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?


回答1:


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.




回答2:


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']


来源:https://stackoverflow.com/questions/29787289/how-to-get-current-locale-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!