Skip to content Skip to sidebar Skip to footer

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-visibl

Solution 1:

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

<ahref="<?phpecho$_SERVER['PHP_SELF']; ?>?lang=fr">French Language</a>

Post a Comment for "Dynamically Switch Content In Website Based On User Language Selection"