note 59032 deleted from reserved.variables by nlopess

From: Date: Thu, 24 Nov 2005 16:52:02 +0000
Subject: note 59032 deleted from reserved.variables by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-99040@lists.php.net to get a copy of this message
Note Submitter: ceres AT divxmania DOT it Reason: bad code ---- Here's my method to load a language file based on languages set on browser. Let's suppose you have language files in "./lang" dir, filenames are in this format: lang_XX-xx.php / lang_XX.php ie: lang_EN-us.php, lang_IT.php, lang_PT.php... Things to do: - load default language and store in a temp variable; - check user accepted language(s) - try to load the best language file - store default language in user session - merge missing strings with default ones <?php define('LANG_DIR', './lang/'); //Return an ordered array like this: //Array //( // [EN-US] => 0.3000007876 // [EN] => 0.7000002402 // [IT] => 1.0000007425 //) function ListLang() { $pref=array(); foreach( split(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"]) as $lang ) { if ( preg_match('/^([a-z\-]+).*?(?:;q=([0-9.]+))?/i', $lang.';q=1.0', $split) ) { $pref[strtoupper($split[1])] = sprintf("%f%d", $split[2], rand(0,9999)); } } asort($pref); return $pref; } //Load default language file include(LANG_DIR."lang_EN.php"); //..and store in a temp variable $tmp_lng = $lang; //Lang was specified in query: index.php?language=EN //so load this lang and store in session if ($_GET['language']) { include(LANG_DIR."lang_".$_GET['language'].".php"); $_SESSION['language'] = $_GETi['language']; } //Lang is already stored in session else if ($_SESSION['language']) { include(LANG_DIR."lang_".$_SESSION['language'].".php"); } //try to find best language and store in session else { $langs = ListLang(); //try to load an accepted language, from worst to best foreach ($langs AS $langf => $imp) { //try specific lang (ie: EN-us, PT-br, IT-ch...) if (is_file(LANG_DIR."lang_".$langf.".php")) { include(LANG_DIR."lang_".$langf.".php"); $_SESSION['language'] = $langf; } //try generic lang (ie: EN, PT, IT...) elseif (is_file(LANG_DIR."lang_".substr($langf,0,2).".php")) { include(LANG_DIR."lang_".substr($langf,0,2).".php"); $_SESSION['language'] = $langf; } } } //fill missing strings with default ones foreach ($tmp_lng AS $ch => $va) { if ($lang[$ch] == '') $lang[$ch] = $va; } ?>

« previous php.notes (#99040) next »