You should pull the locale from the LANG environment variable as LC_ALL may not be set. This may not be Windows compatable, if you need it to be let me know and I'll update it.
//default locale to use when all else fails
define('DEFAULT_LANG', 'en_US.UTF-8');
/**
* returns the current locale based on the LANG environment variable.
* Only calls getenv() once, after that uses a cached value. remove the static
* keyword to disable this functionality.
*
* @return string returns the current locale, or DEFAULT_LANG on error.
*/
function get_lang() {
static $lang; //static variable, so the resulting call to getenv() only fire once
if (!isset($lang) || $lang=="") {
$lang = getenv('LANG');
if (trim($lang)=='')
$lang = DEFAULT_LANG;
}
return $lang;
}
/**
* @param string $text string to translate
* @param string $locale locale to translate to, i.e. de_DE
* @param boolean $provideFallback - provide the original local as a fallback if locale is not recognized
* @return boolean|string returns $text translated to $locale, or FALSE on error.
*/
function translate($text, $locale, $provideFallback = FALSE, $resetLocale = TRUE) {
if ((empty($locale) || trim($locale)=='') && !$provideFallback)
return FALSE;
if (empty($text))
return $text;
$original = get_lang();
//provide a fallback locale in case $locale is not recognized.
if ($provideFallback) {
$l = strval($locale);
if (empty($locale) || trim($locale)=='')
$l = $original; //set locale to the original locale, since none was provided.
$locale = array($l, $original, DEFAULT_LANG);
}
setlocale(LC_ALL, $locale);
$translated = _($text);
if ($resetLocale) {
setlocale(LC_ALL, $original);
}
return $translated;
}
echo get_lang().PHP_EOL;
echo translate("test1", "de_DE.UTF-8") . PHP_EOL;
echo translate("test2", "de_DE.UTF-8") . PHP_EOL;