Yii 1.1: Translation from .txt file

4 followers

Translation from .txt file Note:

  • I have created this functionality as of my project requirement so it is not best matched with yii translation.
  • Give your suggestion for new update i will update it here.

  • Soon i will update this functinality same as yii method with category selection


1. First Create file in path-to-app/protected/messages/langfoldername/lang.txt e.g. for spanish language you have to create file like

    path-to-app/protected/messages/es/es.txt

In you text file you can add translation as below

#Software Title
        Event Tracking = Seguimiento de Eventos
 
#Menus
 
    #Top Menu
 
        Welcome         = Bienvenido
        My Profile      = Mi Perfil
        Change Password = Modificar Contraseña
        Log Out         = Cerrar Sesión
 
    #Middle Menu/Titles
 
        Home            = Inicio
        User            = Usuario
        Users           = Usuarios
        Company         = Compañía
        Companies       = Compañías
        Persons         = Personas
        Person          = Persona
        Event           = Evento
        Events          = Eventos
        Agreement       = Acuerdo
        Agreements      = Acuerdos
        Task            = Tarea
        Tasks           = Tareas

** 2 Create Component path-to-app/protected/components/Translate.php**

<?php
class Translate{
 
    public $language    = "you language constant or variable or session variable";
    private $lang       = array();
    private $path;
 
    private static function findString($str,$lang,$language) {
 
 
        if (array_key_exists($str, $lang[$language])) {
            return $lang[$language][$str];
            return;
        }
        else if (array_key_exists(strtolower($str), $lang[$language])) {
            return $lang[$language][strtolower($str)];
            return;
        }
 
        return $str;
    }
 
    private function splitStrings($str) {
        return explode('=',trim($str));
    }
 
    public static function __($str) {
 
        $language = LANG;
        $lang     = array();
 
        if($language == "en")return $str;
 
        $path = Yii::app()->basePath."/messages/es/".$language.'.txt';
 
        if (!array_key_exists($language, $lang)) {
 
            if(file_exists($path)) {
 
                $txt_arr = file($path);
 
 
                foreach($txt_arr  as $val){
                    $strings[] = explode('=',trim($val));
                }
 
                foreach ($strings as $k => $v) {
 
                    if(!empty($v[0]) && !empty($v[1]))
                        $lang[$language][trim($v[0])] = trim($v[1]);
 
                }
 
                return self::findString($str,$lang,$language);
            }
            else {
                return $str;
            }
        }
        else {
            return self::findString($str,$lang,$language);
        }
    }
    public static function t($str) {
        return self::__($str);
    }
}
?>

**3. Usage : ** Translate::__("Your String here");

Translate Menu items

$this->widget('zii.widgets.CMenu',array(
 
            'items'=>array(
 
                array(
                    'label'   => Translate::__("Home"),
                    'url'     => array('/site/index'),
                    'visible' => !Yii::app()->user->isGuest,
 
                ));

Translate Model Atrributes

public function attributeLabels()
    {
        return array(
            'event_id'          => Translate::__('ID'),
            'person_id'         => Translate::__('Author'),
            'company_id'        => Translate::__('Company'),
            'name'              => Translate::__('Event Name'),
            'creation_date'     => Translate::__('Creation Date'),
            'date'              => Translate::__('Event Date'),
            'notes'             => Translate::__('Notes'),
            'event_type'        => Translate::__('Event Type'),
            'company_name'      => Translate::__('Company'),
            'person_first_name' => Translate::__('Author'),
            'task_name'         => Translate::__('Task')
        );
    }

Translate Flash messages

$message = Translate::__("Data Inserted Successfully");
Yii::app()->user->setFlash("success", $message); // Flash Message

Total 6 comments

#18050 report it
nachi at 2014/09/02 04:47am
Strange inheritance

Whether it is the best method to do multilingual sites ?

#18036 report it
guaruja at 2014/08/29 07:59am
Problematic separator

When the text to translate/translated text contains "=" your solution will produce some unwanted results (due to the simple explode strategy). So for real life (complex) applications your approach might be too simple. Btw: the Yii built-in l18n functionality is quite good and i do not see any additional benefit from your solution (besides using .txt files instead of .php, but this can easy achieved by overriding yii core translate functionalities)

#18014 report it
Yatin Mistry at 2014/08/26 07:57am
Strange inheritance

Yes. I have already read this and used also.

#18013 report it
Jmper at 2014/08/26 07:48am
Strange inheritance

I just wanted to point that what you are presenting can be achieved easier by extending CMessageSource. You could then benefit from some sophisticated translation features Yii provides, like format choices or plural forms. Read this section of the guide for more information.

#18012 report it
Yatin Mistry at 2014/08/26 07:37am
Strange Inheritance

Hello Jmper ,

You are right. There is no requirement to inherit CController class. Thanks for the comment.

Yes. Yii gives solution for translation But This is requirement in my application by client to do the same so i sharing how to do the same from .txt file?

#18011 report it
Jmper at 2014/08/26 07:27am
Strange inheritance

Why do you inherit from CController? CComponent would be more appropriate. But, what's more important, why don't you use CMessageSource and inherit from it? You'd only need to overwrite translate() function and then the whole solution would fit neatly into Yii translation framework.

Leave a comment

Please to leave your comment.

Write new article
  • Written by: Yatin Mistry
  • Category: Tutorials
  • Yii Version: 1.1
  • Votes: +1 / -4
  • Viewed: 1,784 times
  • Created on: Aug 26, 2014
  • Last updated: Sep 10, 2014
  • Tags: translation