使用PHP在网站上切换语言

使用PHP在网站上切换语言

本文介绍了使用PHP在网站上切换语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在寻找一些建议.我正在创建一个提供(至少)两种语言的网站.我的设置方法是使用XML语言文件,PHP检索XML节点中的值.假设您有任何XML文件,正在按以下方式加载:

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");
?>

一旦文件内容可用,我就将每个节点输出到HTML标记中,如下所示:

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.

现在,切换语言的方式是通过"$ _POST"来更改"$ lang"变量的值,如下所示:

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";
}

重置"$ lang"变量的值并加载新文件,并从新XML文件中加载所有新节点,从而更改语言.

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.

我只是想知道是否还有其他方法可以使用"$ _POST"或"$ _GET"以外的其他方式重置"$ lang"变量.我也不想使用查询字符串.我知道我可以使用JavaScript或jQuery来实现此目的,但我想使该站点不太依赖JavaScript.

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.

谢谢

推荐答案

我会选择会话变量.

在页面的开头,您将拥有:

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就像

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

这篇关于使用PHP在网站上切换语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 04:48