Switching languages on a website with PHP

jnkrois picture jnkrois · May 21, 2010 · Viewed 8.3k times · Source

I'm just looking for some advice. I'm creating a website that offers (at least) 2 languages. The way I'm setting it up is by using XML files for the language, PHP to retrieve the values in the XML nodes. Say you have any XML file, being loaded as follows:

<?php
$lang = "en";
$xmlFile = simplexml_load_file("$lang/main.xml");
?>

Once the file contents are available, I just output each node into an HTML tag like so:

<li><?php echo $xmlFile->navigation->home; ?></li>
which in turn is equal to : <li><a href="#">Home</a></li>
as a nav bar link.

Now, the way in which I'm switching languages is by changing the value of the "$lang" variable, through a "$_POST", like so:

if(isset($_POST['es'])){
$lang = "es";
}elseif(isset($_POST['en'])){
$lang = "en";
}

The value of the "$lang" variable is reset and the new file is loaded, loading as well all the new nodes from the new XML file, hence changing the language.

I'm just wondering if there is another way to reset the "$lang" variable using something else, other than "$_POST" or "$_GET". I don't want to use query string either. I know I could use JavaScript or jQuery to achieve this, but I'd like to make the site not too dependable on JavaScript.

I'd appreciate any ideas or advice.

Thanks

Answer

nico picture nico · May 21, 2010

I would go for session variable.

At the beginning of your pages you'll have:

 if (!isset($_SESSION['language']))
    $_SESSION['language'] = "en";

Then you'll have some links to change the language

<a href="changelanguage.php?lang=es">Español</a>
<a href="changelanguage.php?lang=fr">Français</a>

Changelanguage.php simply is something like

$language = $_GET['lang'];
// DO SOME CHECK HERE TO ENSURE A CORRECT LANGUAGE HAS BEEN PASSED
// OTHERWISE REVERT TO DEFAULT
$_SESSION['language'] = $language;
header("Location:index.php"); // Or wherever you want to redirect