I use the following code to change the language in my website:
<?php
session_start();
header('Cache-control: private'); // IE 6 FIX
function get_lang(){
if(!empty($_GET['lang'])) return $_GET['lang'];
if(!empty($_SESSION['lang'])) return $_SESSION['lang'];
if(!empty($_COOKIE['lang'])) return $_COOKIE['lang'];
return 'en';
}
function set_lang($lang){
setcookie("lang", $lang, time() + (3600 * 24 * 30));
$_SESSION['lang'] = $lang;
}
function get_lang_file($lang){
$lang_file = "languages/lang.$lang.php";
if(file_exists($lang_file)) return $lang_file;
if($lang_file = get_lang_file('en')) return $lang_file;
return false;
}
//translation helper function
function l($string){
static $translation;
if(!isset($translation)){
$lang = get_lang();
$lang_file = get_lang_file($lang);
if($lang_file) set_lang($lang);
$translation = include $lang_file;
}
return $translation[$string];
}
?>
I want to add a Javascript file according to the value of one of the variables, in this case $lang_file
:
<?php if($lang_file=='lang.en.php') {echo ' <script type="text/javascript" src="scripts/jquery-validate/val-en.js"></script>';} ?>
<?php if($lang_file=='lang.es.php') {echo ' <script type="text/javascript" src="scripts/jquery-validate/val-es.js"></script>';} ?>
<?php if($lang_file=='lang.tw.php') {echo ' <script type="text/javascript" src="scripts/jquery-validate/val-tw.js"></script>';} ?>
<?php if($lang_file=='lang.cn.php') {echo ' <script type="text/javascript" src="scripts/jquery-validate/val-cn.js"></script>';} ?>
But it doesn't work because all the variables become NULL
at the end (but the code works).
I tested it with this and it says NULL NULL NULL NULL:
var_dump($translation);
var_dump($lang);
var_dump($string);
var_dump($lang_file);
Any suggestions?
EDIT: sample of the Javascripts I'm calling (val-xx.js
):
$(document).ready(function(){
$("#sendmail").validate({
rules: {
FieldData0: {
required: true
},
FieldData1: {
required: true,
email: true
},
FieldData2: {
required: true
}
},
messages: {
FieldData0: {
required: "Please enter your name"
},
FieldData1: {
required: "Please enter your email address"
},
FieldData2: {
required: "Please enter a message"
}
}
});
})
a sample of a lang.$lang.php file:
<?php
return array(
'tagline_h2' => '我创造简单...',
(and so on)