使用php在网站上使用2种语言

时间:2012-06-06 11:58:24

标签: php cookies

帮助请组织双语网站。

首先,有两个文件eng.php,es.php,它们将存储在翻译网站中。

示例:

$lang['hi'] = 'Hi';

如何在网站上组织进一步的语言选择并在Cookie中记录有关语言的信息?

2 个答案:

答案 0 :(得分:2)

你可以有两个这样的文件。

en.php的来源:

$lang = array(
    'hi' => 'Hi'
);

es.php的来源:

$lang = array(
    'hi' => 'Hello'
);

对于主要内容文件,源应该是这样的:

<?php
    session_start(); // Make sure you initialize cookies / session
    $allowedLangs = array('en', 'es'); // Array with allowed values
    if(isset($_SESSION['lang'])) { // If already user had stored language in session
        include $_SESSION['lang'] . ".php";
    } elseif(isset($_GET['lang']) && in_array($_GET['lang'], allowedLangs)) { // If user had requested like index.php?lang=en
        include $_GET['lang'] . ".php";
        $_SESSION['lang'] = $_GET['lang']; // Update the session with the language
    } else { // If user is visiting for the first time, then...
        include "en.php";
    }

    echo $lang['hi'];
?>

答案 1 :(得分:0)

<?php
    if(!isset($_COOKIE['lang'])){
        ?>
        Choose Language...
        <a href="es.php">ES</a><a href="eng.php">ENG</a>
        <?php
    } else {
        if($_COOKIE['lang']=='es'){
            header("location:es.php");
        }
        elseif($_COOKIE['lang']=='eng'){
            header("location:eng.php");
        }
    }
?>

es.php // eng.php

<!--Your Content-->
<?php
    setcookie("lang","es/eng",time()+SECONDS_YOU_WANT)
?>