Translation from .txt file

You are viewing revision #10 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#9)

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