我想用php國際化我的網站。我對PHP非常陌生!
的index.php
啓動與此:
<?php session_start(); ?>
<?php include 'api/locale.php'; ?>
<html>
<!-- ... -->
<div><?php loc('foo') ?></div>
的locale.php
看起來是這樣的:
<?php
if(isset($_GET['lang']) {
$_SESSION['lang'] = $_GET['lang'];
} else {
$_SESSION['lang'] = 'en'; // default value
}
// use the necessary language file
include('/locale/' . $_SESSION['lang'] . '.php');
// get phrase from URL
if (isset($_GET["phrase"]))
loc($_GET["phrase"];);
function loc($phrase)
{
global $lang;
if(array_key_exists($phrase, $lang)) {
echo $lang[$phrase];
} else {
echo $phrase;
}
}
?>
的想法是我想使用的功能loc($phrase)
獲取內容無論是在德語或英語。但這裏是問題:
如果我有這樣的代碼,我總是得到英文版本,因爲在locale.php
我無法從網址獲得lang
:$_GET['lang']
未定義。因此,會話語言始終設置爲默認語言(en)。
但是,如果我移動session_start();
到文件locale.php
,國際化的工作原理:
index.php
:
<?php include 'api/locale.php'; ?>
<html>
<!-- ... -->
<div><?php loc('foo') ?></div>
locale.php
:
<?php
session_start();
if(isset($_GET['lang']) {
$_SESSION['lang'] = $_GET['lang'];
// ... rest the same as above
爲什麼會這樣呢?我在做一些概念上的錯誤?問題是,我也是用這個locale.php
在Ajax調用來獲得國際內容動態生成HTML元素:
function loc(phrase)
{
var locString;
$.ajax({
// force synchronous ajax call, to return with locString
async: false,
// url with to be translated id
url: "api/locale.php?phrase=" + phrase,
// "get" for small data (otherwise post)
method: "get",
// callback function after server has reveiced information
success: function (data)
{
locString = data;
}
});
return locString;
}
所以,如果我一遍又一遍地打電話locale.php
這個AJAX調用,是不是有開始新的會話一遍又一遍地?我不確定我是否正確設計了我的功能。我對任何評論感到高興!
謝謝!
===============編輯===============
好了,我現在嘗試一種新的方式:
session.php
// session starts at this point session_start(); // internationalisation in EN and DE $allowedLangs = array('en', 'de'); // check lang-parameter given in URL and set language from there if(isset($_GET['lang']) && in_array($_GET['lang'], $allowedLangs)) $_SESSION['lang'] = $_GET['lang']; if(!isset($_SESSION['lang'])) $_SESSION['lang'] = 'en'; // default value
locale.php
// include correct languguage file $root = realpath($_SERVER["DOCUMENT_ROOT"]) ; include($root . '/locale/' . $_SESSION['lang'] . '.php'); // get phrase from URL and translate it if (isset($_GET["phrase"])) { $phrase = $_GET["phrase"]; global $lang; if (array_key_exists($phrase, $lang)) echo $lang[$phrase]; else echo $phrase; }
兩個文件會包含在index.php
<?php include 'api/session.php'; ?>
<?php include 'api/locale.php'; ?>
但是,如果我現在語言環境的短語與阿賈克斯,出現以下錯誤信息:
Notice: Undefined variable: _SESSION in ... /locale.php on line 4
怎麼可能?我以爲$_SESSION
是超全球?!?
你應該仍然可以在'include'd和'require'd文件中訪問'$ _GET' ... – Ryan 2013-04-20 22:33:32