Most efficient way to do language file in PHP?

Viewed 45430

Questions Updated instead of making a new question...

I really want to provide a few alternative languages other then English on my social network site I am building, this will be my first time doing any kind of language translation so please bear with me.
I am researching so I am al ear and open to ideas and I have a lot already here is are the questions.

1)
What does i18n mean, I see it often when researching language translation on SO?

2)
Most people say use gettext PHP has an extension or support for it,
well I have been researching it and I have a basic understanding of it, as far as I can tell it is a lot of extra work to go this route,
I mean coding my site to use it's functions ie; _('hello world i'm in English for now') or else gettext('hello world i'm in English for now') is no problem as any route I go will require that.
But then you have to install gettext on your server and get it working,
then use some special editors to create special files and compile them I think?

Sounds like a pain, I understand this is supposed to be the best route to go though, well everyone seems to say it is.
So can someone tell me why this is the route to go?

3)
I really like the simplicity of this approach, just building a language array and calling the phrase you need in a function like the example below , you would then just include a file with the appropriate language array.

What I really want to know is, would this be the less better performance method on a high traffic and fairly large site compared to using gettext and if so can you explain why please?

<?PHP
//Have seperate language files for each language I add, this would be english file
function lang($phrase){
    static $lang = array(
        'NO_PHOTO' => 'No photo\'s available',
        'NEW_MEMBER' => 'This user is new'
    );
    return $lang[$phrase];
}
//Then in application where there is text from the site and not from users I would do something like this
echo lang('NO_PHOTO');  // No photo's available would show here
?>

* some code used from brianreavis's answer below

9 Answers

This might work better:

function _L($phrase){
static $_L = array(
    'NO_PHOTO' => 'No photo\'s available',
    'NEW_MEMBER' => 'This user is new'
);

     return (!array_key_exists($phrase,$_L)) ? $phrase : $_L[$phrase];
}

Thats what i use for now. If the language is not found, it will return the phrase, instead of an error.

You should note that an array can contain no more than ~65500 items. Should be enough but well, just saying.

Here's some code that i use to check for the user's language:

<?php
function setSessionLanguageToDefault() {
    $ip=$_SERVER['REMOTE_ADDR'];
    $url='http://api.hostip.info/get_html.php?ip='.$ip;
    $data=file_get_contents($url);
    $s=explode (':',$data);
    $s2=explode('(',$s[1]);

    $country=str_replace(')','',substr($s2[1], 0, 3));

    if ($country=='us') {
        $country='en';
    }

    $country=strtolower(ereg_replace("[^A-Za-z0-9]", "", $country ));
    $_SESSION["_LANGUAGE"]=$country;
}

if (!isset($_SESSION["_LANGUAGE"])) {
    setSessionLanguageToDefault();
}

if (file_exists(APP_DIR.'/language/'.$_SESSION["_LANGUAGE"].'.php')) {
    include(APP_DIR.'/language/'.$_SESSION["_LANGUAGE"].'.php');
} else {
    include(APP_DIR.'/language/'.DEFAULT_LANG.'.php');
}

?>

Its not done yet, but well i think this might help a lot.

You can do this:

class T {
const language = "English";
const home = "Home";
const blog = "Blog";
const forum = "Forum";
const contact = "Support";
}

You would have a file like this for each language. To use the text:

There is no place like <?=T::home?>.

The downside is that if you add a new constant, you have to do it for every langauge file. If you forget one, your page breaks for that language. That is a bit nasty, but it is efficient since it doesn't need to create a large associative array and possibly the values even get inlined.

Maybe access could be improved, eg:

class T {
    const home = "home";

    public static function _ ($name) {
        $value = @constant("self::$name");
        return $value ? $value : $name;
    }

    // Or maybe through an instance:
    public function __get ($name) {
        $value = @constant("self::$name");
        return $value ? $value : $name;
    }
}
echo "There is no " . T::_("place") . " like " . T::_("home");
$T = new T();
echo "There is no " . $T->place . " like " . $T->home;

We still avoid the array and rely on constant to do the lookup, which I assume is more expensive than using the constants directly. The up side is the lookup can use a fallback when the key is not found.

An extension to the answers above whom deserve the credit - I'm just posting as maybe this will also be useful to someone else who ends up here.

I personally prefer the key to the array to be the actual phrase in my mother tongue (in my case English) rather than a CONSTANT_VALUE because:

  • I find it easier to read the code when the text is in my native language rather than having to remember what a CONSTANT_VALUE actually outputs
  • It means no lookup is needed to return the phrase for visitors who also use my naitive language (giving marginally better performance)
  • It's one less list of values to maintain

The downside is that it's harder to spot missing values in other languages as you don't necessarily have a master list anymore - I also log a warning from the abstract method so that I spot any missing values.

I implemented as:

  • An abstract class with static methods for outputting the text value (using late static binding)
  • A concrete class for each language: English overriding the method to return the phrase without translation, other languages overriding the list of phrases so that a translated phrase is returned
    <?php
    namespace Language;

    abstract class _Language
    {
        protected static $displayText = array();

        public static function output($phrase){
            return static::$displayText[$phrase] ?? $phrase;
        }
    }
    <?php
    namespace Language;

    class English extends _Language
    {
        public static function output($phrase){
            return $phrase;
        }
    }
    <?php
    namespace Language;

    class Spanish extends _Language
    {
        protected static $displayText = array(
            'Forename' => 'Nombre',
            'Registered Email' => 'Correo electrónico registrado',
            'Surname' => 'Apellido'
        );
    }

Usage:

    $language = new \Language\Spanish();
    echo $language::output('Forename'); // Outputs: Nombre
    $language = new \Language\English();
    echo $language::output('Registered Email'); // Outputs: Registered Email

Unfortunately gettext not work good and have problems in various situation like on different OS (Windows or Linux) and make it work is very difficult.

In addition it require you set lot's of environment variables and domains and this not have any sense.

If a developer want simply get the translation of a text he should only set the .mo file path and get the translation with one function like translate("hello","en_EN"); With gettext this is not possible.

Related