Use PHP Gettext without having to install locales

a 夏天 提交于 2019-12-03 12:20:51

Try gettext-php. It is a drop-in replacment for gettext written in PHP. It was originally done for WordPress, I think, because WP needs to run on shared hosts which are not always configured for every locale. This seems to me to be your issue as well.

It has a bit of performance hit, but it has not been an issue for me at all.

Here is the solution:

$lang = 'de'; //debug
setlocale( LC_ALL, 'C.UTF-8' );
bindtextdomain( 'default', PATH . "/locale/$lang" );
bind_textdomain_codeset( 'default', 'UTF-8' );
textdomain( 'default' );

The only difference between that and the example I posted at the bottom of my answer is that it uses C.UTF-8 not just C.

I'll be doing more testing of this, and if it works cross-platform, and will update this answer if I find out anything else.

For anyone still having some problem with this, you can try the code below, which i get from here: http://php.net/manual/en/function.gettext.php#58310

It solved me on freebsd server, having no extra locale install (fr_FR and my_MY) This code is also useful when you have some problem with the gettext cache.

<?php
function initialize_i18n($locale) {
  $locales_root="/app/php/locale"; // change This to where you locale folder at
  putenv('LANG='.$locale);
  setlocale(LC_ALL,"");
  setlocale(LC_MESSAGES,$locale);
  setlocale(LC_CTYPE,$locale);
  $domains = glob($locales_root.'/'.$locale.'/LC_MESSAGES/*.mo');
  $current = basename($domains[0],'.mo');
  $timestamp = preg_replace('{messages-}i','',$current);
  bindtextdomain($current,$locales_root);
  textdomain($current);
}
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!