Skip to content
Advertisement

Implementation of multilanguage in PHP

I was wondering how to implement multiple languages in PHP script. I couldn’t really find any handy way of how such thing should be done to make it easy for translator. I’ll give an example:

//Output looks like this:
//Where are You, Mike? It is me, Rebeca! I am waiting here for 5 hours!

//But in file it is some abomination like:
echo 'Where are You, '.$name.'? It is me, '.$name2.'! I am waiting here for '.$time.' hours!';

//Just imagine that meantime there might be different functions, included files
//and other code required to create more sentences like the above to create long text...

If the file outputs such text shattered by many different variables and code, how the language file should look like?

I came up with idea to keep the user language in $_SESSION[‘lang’], and in each file include file with correct language. But after I tried to do so, it does look like this:

//main file
echo $txt[1].$name.$txt[2].$name2.$txt[3].$time.$txt[3];

//lang file
$txt[1] = 'Where are You, ';
$txt[2] = '? It is me, ';
$txt[3] = '! I am waiting here for ';
$txt[3] = ' hours!';

It looks ridiculous, unreadable, and with many potential mistakes. And just imagine if You are translator that gets access only to the lang file – it is impossible to translate such text, right? How this should/could be done differently?

Advertisement

Answer

Yes, its done like that but not individual words or blocks of the sentence like your doing, else it would not translate well.

How it’s generally done to handle the problem, you define your templates and then have a function which you call with passed params.

see: https://www.php.net/manual/en/refs.international.php for getext etc, or find a lib.

Example:

<?php
$trans = [
    'en' => [
        'user_where_are_you_text' => 'Where are You, %s? It is me, %s! I am waiting here for %s hours!',
        //...
    ],
    'fr' => [
        'user_where_are_you_text' => 'Où es-tu, %s? C'est moi, %s! J'attends ici depuis %s heures!'
        //...
    ],
    //...
];

$name = 'Loz';
$name1 = 'Rasmus';
$time = 3;

function __($key, ...$arguments) {
    global $trans, $lang;
    return sprintf($trans[$lang][$key], ...$arguments);
}

//
$lang = 'en';
echo __('user_where_are_you_text', $name, $name1, $time).PHP_EOL;

//
$lang = 'fr';
echo __('user_where_are_you_text', $name, $name1, $time).PHP_EOL;

https://3v4l.org/e1nEB

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement