Dynamically switch content in website based on user language selection

隐身守侯 提交于 2019-12-11 07:41:39

问题


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.


回答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

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


来源:https://stackoverflow.com/questions/18548373/dynamically-switch-content-in-website-based-on-user-language-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!