Skip to content

Instantly share code, notes, and snippets.

@fcamel
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcamel/0b64ba0bf6317736f908 to your computer and use it in GitHub Desktop.
Save fcamel/0b64ba0bf6317736f908 to your computer and use it in GitHub Desktop.
PHP and JavaScript Localization
<?php
$g_default_lang = "en";
$g_messages = array();
function get_target_language() {
global $g_default_lang;
if (isset($_GET['lang'])) {
return $_GET['lang'];
}
if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
return $g_default_lang;
}
$lang_list = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$langs = array();
$lang_ranges = explode(',', trim($lang_list));
foreach ($lang_ranges as $lang_range) {
if (preg_match('/(\*|[a-zA-Z0-9]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?/', trim($lang_range), $match)) {
if (!isset($match[2])) {
$match[2] = '1.0';
} else {
$match[2] = (string) floatval($match[2]);
}
if (!isset($langs[$match[2]])) {
$langs[$match[2]] = array();
}
$langs[$match[2]][] = $match[1];
}
}
if (empty($langs)) {
return $g_default_lang;
}
krsort($langs);
return array_shift(array_shift($langs));
}
function setup_l10n($lang) {
global $g_default_lang;
// Read default language.
$json = file_get_contents("_locales/$g_default_lang/messages.json");
if ($json === FALSE) {
return FALSE;
}
$dict = json_decode($json);
// Read target language.
$lang = str_replace("-", "_", $lang);
$json = file_get_contents("_locales/$lang/messages.json");
if ($json === FALSE) {
$lang = array_shift(explode("_", $lang));
$json = file_get_contents("_locales/$lang/messages.json");
}
if ($json !== FALSE) {
$tmp = json_decode($json);
foreach ($tmp as $key => $value) {
$dict->$key = $value;
}
}
$json = json_encode($dict);
return array($dict, $json);
}
function _m($key) {
global $g_messages;
if (array_key_exists($key, $g_messages)) {
return $g_messages->$key->message;
}
return $key;
}
$lang = get_target_language();
$result = setup_l10n($lang);
if ($result !== FALSE) {
$g_messages = $result[0];
echo "<script>\n";
echo "var g_messages = " . rtrim($result[1]) . ";\n";
echo "\n";
echo <<<EOT
function _m(key) {
if (key in g_messages) {
return g_messages[key].message;
}
return key;
}
EOT;
echo "</script>\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment