preahkumpii
preahkumpii

Reputation: 1301

Dynamically switch content in website based on user language selection

I am designing a small, simple website that will need two languages. I want to keep things simple. I would like to use placeholders/variables in the code that will have user-visible text. Then, allow the user to the select the language of his choice (using a simple link), and make the entire site's text switch over to that language. I would prefer something similar to a language file, in which the values in the code are simply switched when the user selects his language. Below is a small example to illustrate what I am referring to.

<div class='title'>
  [$siteTitleGoesHere]
</div>

I hope that makes sense. I am familiar enough with php and javascript that I might be able to use them to do this, if given direction. Thanks for any help.

Upvotes: 1

Views: 4162

Answers (1)

Dale
Dale

Reputation: 10469

Here's one approach..

Create a folder called lang

Inside this folder create your language files, lets say en.php and fr.php

These files contain an array called $lang that contains all the swappable text for your site.

for example in en.php

$lang['header'] = 'Welcome to my site!';

and in fr.php

$lang['header'] = 'Bonjour!'; // my french is awesome

You can then load the right file based on (for example) a session value

session_start();
if ( ! isset($_SESSION['lang'])) $_SESSION['lang'] = 'en';
require ("lang/{$_SESSION['lang']}.php");

echo $lang['header'];

If you wanted to change the language you could do something like this

in your php you will need to switch the session lang value to the new language

if (isset($_GET['lang']))
{
    $_SESSION['lang'] = $_GET['lang'];
    header("Location: {$_SERVER['PHP_SELF']}");
    exit;
}

And you would use a link like this

<a href="<?php echo $_SERVER['PHP_SELF']; ?>?lang=fr">French Language</a>

Upvotes: 3

Related Questions