phptranslate

Core PHP Site translate to other language


I have create array $_en to store English words/sentences and $_no array to store Norwegian text to use it as translation for my core PHP project.

<?php
$_en = array(
    'mail' => 'email',
    'msg1' => 'how are you?'
    
);
$_no = array(
    'mail' => 'epost',
    'msg1' => 'hvordan har du det ?'
);

echo "EMAIL IN ENGLISH:".$_en['mail']."\n"; //email in english
echo "EMAIL IN NORWEGIAN:".$_no['mail']; //email in NORWEGIAN
echo "Message IN NORWEGIAN:".$_no['msg1']; //Message in NORWEGIAN

Based on the array and the key value the text will be called based on the site translation function.

Any better solutions and enhancements are most welcome.


Solution

  • A better solution, as mentioned my Thamilan in the comments would be to use a class to handle conversions.

    Think of it like this;

    Your Template File

    $trans = new Translate('en');
    <h1><?php echo $trans->__('This is a title'); ?></h1>
    

    Translate.php

    class Translate {
        public function __construct($lang) {
            $this->lang = $lang;
        } 
    
        public function __($string) {
            // $translatedString = $this->getTranslatedString($string);
            return $translatedString;
        }
    }
    

    In this class, you'll need to fetch the translation from where it's stored. You could store in in this class in an array, or a better solution would be to load them from a CSV file.