7

在 PHP 中,我想在单击按钮时更改站点的语言(英语、德语等)。这是解决该问题的正确方法吗?

<?php 
  $language;
  if ($language == "en") {
    include("headerEn.php");
  } else {
    include("header.php");
  } 
?>
<a href="index.php"><?php $language = "en"; ?>
<img src="images/language/languageNO.png"></a>

<a href="index.php"><?php $language = "no"; ?>
<img src="images/language/languageEN.png"></a>

更改网站语言并在用户返回时保持不变的最佳方法是什么?

4

7 回答 7

10

你可以这样做

<a href="index.php?language=en">
<a href="index.php?language=no">

并获取语言并将它们存储在 cookie 中并根据 cookie 包含文件,例如

if ( !empty($_GET['language']) ) {
    $_COOKIE['language'] = $_GET['language'] === 'en' ? 'en' : 'nl';
} else {
    $_COOKIE['language'] = 'nl';
}
setcookie('language', $_COOKIE['language']);

然后

if ( $_COOKIE['language'] == "en") {
   include("headerEn.php");
} else {
   include("header.php");
} ?>
于 2013-02-25T13:32:01.317 回答
3

To give a solution without changing your approach, You can do like this.

<?php 
if(isset($_GET['language']))
  $language = $_GET['language'];
else
  $language = "";

if ($language == "en") {
   include("headerEn.php");
} else {
   include("header.php");
} ?>

<a href="index.php?language = en"><img src="images/language/languageNO.png">      </a>
<a href="index.php?language = no"><img src="images/language/languageEN.png"></a>

If you want to keep the selection, you can store this value in Database or Session.

于 2013-02-25T13:34:19.507 回答
3

It is always good to have a default value, so that you never end up being in a no-language site.

$language = $_REQUEST["language"];
$default_header="myheaderXXX.php";

switch ($language) {
    case "en":
      include("headerEn.php");
      break;

    case "no":
      include("header.php");
      break;

    default:
      include($default_header);
}

And then create links like this:

<a href="index.php?language=en">
<a href="index.php?language=no">
于 2013-02-25T13:35:29.693 回答
0

尝试将此$language值保存到会话变量。当页面重新加载时,检查会话变量是否设置。

如果设置使用$language

笔记:

$language = $_GET['language'];
于 2013-02-25T13:33:14.020 回答
0

您不能通过 html 更改 PHP 中的变量。PHP 是服务器端 HTML 是客户端端

您可以使用GET 变量来更改它。这是最简单的方法。

于 2013-02-25T13:33:22.863 回答
0

You can implement the same code like this . I have editted your code .

<?php 
$language; ?>
<?php if ($language == "en") : ?>
    <?php include("headerEn.php"); ?>
     <a href="index.php"><?php $language = "en"; ?><img src="images/language/languageNO.png"></a> 
<?php else: ?>
    <?php include("header.php"); ?>
     <a href="index.php"><?php $language = "no"; ?><img src="images/language/languageEN.png"></a>
<?php endif; ?> 

this will solve your problem .

于 2013-02-25T13:36:56.350 回答
0

In this case I have tried use Session variables to store and define language. Every thing works until i turn on caching. When caching was enabled even reload page returns same language and user could not change language. So I consider to change language using AJAX request after clicking on language button (national flag)

于 2020-08-14T13:01:32.210 回答