How to implement language packs in PHP

我与影子孤独终老i 提交于 2019-12-12 04:25:30

问题


I created 3 language packs for my site: English, Spanish and French. I am just having trouble implementing them based on user selection. I have the following drop down menu:

<select onchange='document.location.href=this.options[this.selectedIndex].value;'>
  <option>Select</option>
  <option value="?lang=eng">US English</option>
  <option value="?lang=esp">Español</option>
    <option value="?lang=fra">Français</option>
</select>

How can I include the language files based on what the user selects, I just don't know what to put as the condition in the if statement.

Thanks.


回答1:


At first, save the value that the user selected in the user session. e.g.:

switch($_POST['lang']) {
    case 'en': $_SESSION['lang'] = 'English'; break;
    case 'sp': $_SESSION['lang'] = 'Spanish'; break;
    default:   $_SESSION['lang'] = 'English'; break;
}

On every page request, fetch the language files from the relevant language folder according to the value the you saved.

For example, this how will look the files structure:

  • English
    • Global.php
    • Register.php
  • Spanish
    • Global.php
    • Register.php

Then, whenever you need to load a text file, use:

function load_text_file($filename) {
    include 'languages/' . $_SESSION['lang'] . '/' . $filename.'php';
    return $txt;    // $txt should be an array
}
//...

$text = array(); $text += load_text_file('Global'); $text += load_text_file('Register');




回答2:


As you're bringing in the option via a query string, you can access it with

$lang = $_GET['lang']



回答3:


For my template, that piece of code is

$_SESSION['language'] = 'english';



来源:https://stackoverflow.com/questions/2169193/how-to-implement-language-packs-in-php

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