问题描述:

So, I have a simple php website. Every single piece of code goes through index.php in the website root, and based on the parameters I get, I include different PHP files for each of the pages. I control most of the settings in my config.php file. Here's the current directory structure, less files not important for this case:

/

/inc/

/inc/config.php

/inc/header.php

/inc/footer.php

/locales/en_US/LC_MESSAGES/messages.po

/locales/en_US/LC_MESSAGES/messages.mo

/index.php

and here's the relevant part of config.php:

$getlang = $_GET["lang"];

if(isset($getlang)) { $lang = $_GET["lang"]; }

$default_lang = "en_US";

if(!isset($lang)) {

$lang = $default_lang;

}

$language = explode('/', $_SERVER["REQUEST_URI"]);

putenv("LANG={$lang}");

setlocale(LC_ALL, $lang);

// Set the text domain as 'messages'

$domain = 'messages';

bindtextdomain($domain, "/var/www/montkucesrbija.com/locales");

bind_textdomain_codeset($domain, 'UTF-8');

textdomain($domain);

So, I'd like to be able to send a GET parameter via URL(like: foobar.com/en_US/mypage), and get that page in given language. Anyhow, what I have now is not working.

网友答案:

You say that you want to use the GET variables, but in your script you create a $language variable that tries to parse the URI and later in your explication you indicate that you want to get the locale from a path such as foobar.com/en_US/mypage

I will take the assumption that you actually want to extract en_US in the url above.

$locale = array_shift(
array_filter(
        explode('/', $_SERVER["REQUEST_URI"])
    )
);

putenv('LANG=' . $locale); // for Apache
putenv('LANGUAGE=' . $locale); // for CLI
setlocale(LC_ALL, $locale . '.utf8');

$domain = 'example';

bindtextdomain($domain, __DIR__ . '/locale');
bind_textdomain_codeset($domain, 'UTF-8');
textdomain($domain);
print _('Hello world');

You need to indicate .utf8 when using setlocale() in Linux, you also need to have the locale installed on the machine to make it work.

You can know which locales are available in bash with this command: locale -a

then the path to your po file is: ./locale/fr_FR/LC_MESSAGES/example.po

it coudl also be: ./locale/fr_FR.utf8/LC_MESSAGES/example.po

But not having utf8 in the path works for me.

Remember that every time you compile your .mo files, you need to restart apache to get the updated strings taken into account.

相关阅读:
Top