简体   繁体   中英

PHP :multi-language issue

I am creating a multilingual site, language switcher loads needed language file but if the file doesn't contain the needed entry, it doesn't appear at all, even default array value is not visible.

I make translation like this:

$lang = "en";
if(isset($_GET['lang'])){ 
    $lang = $_GET['lang']; 
}
require_once("languages/lang_".$lang.".php");

Language array:

<?php echo $language["USERNAME"]; ?>

Language file with translation:

$language["USERNAME"] = "User name";

If language file doesn't include $language["USERNAME"] = "User name" ; then nothing is showing at all. What I am trying to achieve is: if loaded language file doesn't contain the translation, then array should return the default value, example: USERNAME .

I did check if array key or value is available to show needed information, but seems check is done in loaded language file and if the language file is empty, then there is nothing to show. I just need to show default array value which is located in the main PHP file. If there is no translation for array

<?php echo $language["USERNAME"]; ?> 

I want to echo value in brackets: USERNAME .

For that you need to define a default language. In that case i choose English.

In your language files, try not define a variable, but return the translation array.

If you are using return keyword in language files you can have control about variables, so you can include multiple language files in your script.

Language files

lang_en.php

<?php
   return [
       'username' => 'username'
   ];

the same way for the other language files.

index.php

<?php
$lang = "en" // that's default language key
$GLOBALS['defaultLanguage'] = require_once('lang_'.$lang.'.php');

if(isset($_GET['lang'])){
   $lang = $_GET['lang'];
}
$GLOBALS['language'] = include('lang_'.$lang.'.php');

if(!is_array($GLOBALS['language']) {
   $GLOBALS['language'] = [];
}
echo translate('username');

translate function

/**
 * @param string $key
 * @return string
 */
function translate($key)
{
    $language = $GLOBALS['language'];
    $defaultLanguage = $GLOBALS['defaultLanguage'];

    if(!isset($language[$key]) || !$language[$key]){
        $language[$key] = $defaultLanguage[$key];
    }


    return $language[$key];
}

Language array:

$language["USERNAME"] = "User name";

File Script

$lang = "en";
if(isset($_GET['lang'])){ 
    $lang = $_GET['lang']; 
}
require_once("languages/lang_".$lang.".php");
global $templang = $language;

<?php echo language("USERNAME"); ?>

funtion language($key){
    global $templang;
    return (isset($templang[$key]))? $templang[$key] : "Default Value";
}

You can try this:

function getTranslatedText($key) {
    if(array_key_exists($key, $array_contains_translation_text))
        return $array_contains_translation_text[$key];
    else
        return $array_contains_common_text[$key];
}


getTranslatedText("UserName");

Similar to Andrei Todorut answer, you can simply merge 2 language files, replacing default strings with translated, where non-translated will remain untouched. To achieve this, you can use array_replace function, that will do the trick. This will preserve your $language array, no extra functions needed to check for existence of translated string etc.

Let's assume your language file looks like this:

lang_en.php

<?php
  return [
   'username' => 'username',
   'no-trans' => 'not translated'
  ];

lang_other.php

<?php
  return [
   'username' => 'user name'
  ];

Multilingual array code:

<?php
  $lang = "en";
  $defaultLanguage = require_once('lang_'.$lang.'.php');

  if(isset($_GET['lang'])){
    $lang = $_GET['lang'];
  }
  $translated = include('lang_'.$lang.'.php');

  if(is_array($translated)) {
    $language = array_replace($defaultLanguage, $translated);
  } else {
    $language = $defaultLanguage;
  }

Output

  print_r($language);
  // output:
  array[
    'username' => 'user name',
    'no-trans' => 'not translated'
  ]

  echo $language['username'];
  // output:
  user name

So, after discussion with Newcomer and better understanding some requirements, here is another solution to the problem:

Language files

lang_en.php

<?php
  $language["USERNAME"] = "Username";
  $language["EMAIL"] = "Email";
  $language["PASSWORD"] = "Password";
  $language["CREATE_ACCOUNT"] = "Create account"; 

lang_de.php

<?php
  $language["USERNAME"] = "Nutzername";
  $language["PASSWORD"] = "Passwort"; 

Scripts and functions

index.php

<?php
  require_once('translate.php');
  if(isset($_GET['lang']) && file_exists('lang_'.$_GET['lang'].'.php')) {
    include_once('lang_'.$_GET['lang'].'.php');
  } else {
    include_once('lang_en.php');
  }

  // print
  _e('USERNAME');
  // return
  __('USERNAME');

translate.php

<?php
  function _e($key) {
    if(isset($language[$key])) {
      echo $language[$key];
    } else {
      echo $key;
    }
  }

  function __($key) {
    if(isset($language[$key])) {
      return $language[$key];
    } else {
      return $key;
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM