Simple & Easy PHP Translation

Simple & Easy PHP Translation

Translation in an important strategy to attract visitors to your site. Not all visitors can read or speak English therefore one must absolutely provide other language options for users. One widely used method is Gettext however in this tutorial we will explore an other option.

 

Gettext is an extension for PHP that allows people to easily translate websites by using po/mo files along with a software. An alternative solution is to use an associative array then use a simple function to translate the string.

PHP Structure of this method

This method is very simple to implement and to use. The structure of this method is as follows:

- All strings to be translate are wrapped as a parameter of a custom function
- The function uses the string to search an array for a translation
- If found, the function will return the translated string otherwise it will return the initial string

Step 1 - Fetch & Assign Language String

We will first start by creating our function to search language files and fetch the translation of the string. The function name can be anything you want but make sure that the name you choose is not taken by another function otherwise it will result in a fatal error. For this tutorial we will chose e. The function will be as follows.

/**
 * Translate function
 * @param   string $text string to be translated
 * @return  string       translated string
 */
function e(string $text){
  // Get the global variable that contains the translated string
  global $lang;

  // Check if translation exists
  if (isset($lang[$text]) && !empty($lang[$text])) {
    return $lang[$text];
  }

  // else return back $text
  return $text;
}

This is our main function. What it does it first it checks if the global variable $base_lang is defined then it checks if that variable is not English and finally it checks if the translation file exists. If it does exist, it searches the array to find the associated translated string of the input. If it doesn't, it will return the original string.

Step 2 - Create Translation File

The next step is to create the translation files. The name of the file will be the language code that will be used to switch the language. For example, if the name of the file is fr.php then the language code will be fr.

Creating the file is very easy to do and you can use Notepad to create it. First we need to create a empty php file with a very short name. Then we just create an empty array associated to the variable $lang. An example of a sample translation file is shown below.

<?php
   // Name: fr.php
    $lang = array (

       //"String" => "Translated String",
        "Hello" => "Bonjour",
    );

?>

It is very important to not forget any of the quotes and the comma at the end of every line.

Step 3 - Using Translation Function

Now all you have to do is to wrap all strings that you want to translate with the function e or the one you chose at step 1. Below is an example.

<?php echo e("Hello") ?>

Step 4 - Switch Language

Now we just need to add a code to switch the language based on the user's preference and set a cookie to remember it. Here is the code for it.

// Your base language that does not require translation
$base_lang = "en";

// Set the absolute or relative path to you language files
$path_lang = "/PATH/TO";

// Get language from cookie if exists
if(isset($_COOKIE["lang"])){
 $base_lang = $_COOKIE["lang"]; 
}

// Set a language as default using cookies
if(isset($_GET["lang"])){
  
  setcookie("lang", strip_tags($_GET["lang"]), strtotime('+30 days'),'/', NULL, 0);
  
  $base_lang = strip_tags($_GET["lang"]); 
}

// Include the language file if it exists
if(isset($base_lang) && file_exists("{$path_lang}/{$base_lang}.php") && strlen($base_lang) <=3) {
  include("{$path_lang}/{$base_lang}.php");
}

This code simply checks if the parameter lang is set and if it is it will set a cookie that will be used to switch the language if the user revisits the site. The default language can be changed to any languages, provided the file exists, by simply changing the parameter $base_lang.

Step 5 - Create Translation Link

The last step involves the addition of translation links and the codes above to all pages. The easiest way to use the codes above is to add them in a separate PHP file named  translation.php then include it in all of your pages as follows.
<?php 
   include("PATH/TO/translation.php");
?>

Then you just need to add some links in your menu so that users can switch easily switch the language. The easiest way is to use only the paramter lang as follows:

<a href="?lang=YOURLANGUAGECODE">Sample Language</a>

<a href="?lang=fr">French</a>
This will switch the language of the current page provided that the codes above are included in it.

Conclusion & Full Code

Please note that this method is not recommended for large sites or very large strings. Also remember to set the encoding of the PHP translation file to UTF-8 if you intend to use foreign characters. That is it. Enjoy!
<?php

// Your base language that does not require translation
$base_lang = "en";

// Set the absolute or relative path to you language files
$path_lang = "/PATH/TO";

// Get language from cookie if exists
if(isset($_COOKIE["lang"])){
 $base_lang = $_COOKIE["lang"]; 
}

// Set a language as default using cookies
if(isset($_GET["lang"])){
  
  setcookie("lang", strip_tags($_GET["lang"]), strtotime('+30 days'),'/', NULL, 0);
  
  $base_lang = strip_tags($_GET["lang"]); 
}

// Include the language file if it exists
if(isset($base_lang) && file_exists("{$path_lang}/{$base_lang}.php") && strlen($base_lang) <=3) {
  include("{$path_lang}/{$base_lang}.php");
}

/**
 * Translate function
 * @param   string $text string to be translated
 * @return  string       translated string
 */
function e(string $text){
  // Get the global variable that contains the translated string
  global $lang;

  // Check if translation exists
  if (isset($lang[$text]) && !empty($lang[$text])) {
    return $lang[$text];
  }

  // else return back $text
  return $text;
}
?>