In my project I want to send notification emails to multilingual recipients. For this case gettext is already setup and works fine for the website. Every user has a locale attribute, containing his language setting. My code looks like:
$users = [User, User, User, User];
foreach($users as $user) {
$userLocale = $user->getLocale(); // e.g. en_US, de_DE
putenv("LC_ALL=".$userLocale);
setlocale(LC_ALL, $userLocale);
$content = _("Hello there");
$user->sendNotificationMail($content);
}
That code ignores the language just set and translates the string always to its default language the first language set in the loop. (in this case german)
But when I hardcode putenv("LC_ALL=en_US");
it works.
What to I miss here?
EDIT:
Seems like php cant switch the language as many times as I want. First switch is successfull but the following switches seems to fail or gettext doesnt take the changes in consideration.
My testcode:
$payload = "";
putenv("LANG=en_US");
setlocale(LC_ALL, "en_US");
$payload .= _("Add")." - ".getenv("LANG");
putenv("LANG=it_IT");
setlocale(LC_ALL, "it_IT");
$payload .= _("Add")." - ".getenv("LANG");
putenv("LANG=de_DE");
setlocale(LC_ALL, "de_DE");
$payload .= _("Add")." - ".getenv("LANG");
//output: Add - en_USAdd - it_ITAdd - de_DE
//moving de_DE to the top
//output: hinzufügen - de_DEhinzufügen - en_UShinzufügen - it_IT
wtf is going on?
I tried also to delete the first variable setting of $payload
. Then all following gettext calls will use the second language setted.
Seems like that you have to set the textdomain everytime.
putenv("LANG=".$locale);
setlocale(LC_ALL, $locale);
textdomain($domain);