82

I'm researching hours and hours, but I could not find any clear, efficient way to make it :/

I have a codeigniter base website in English and I have to add a Polish language now. What is the best way to make my site in 2 language depending visitor selection?

is there any way to create array files for each language and call them in view files depends on Session from lang selection? I don't wanna use database.

Appreciate helps! I'm running out of deadline :/ thanks!!

designer-trying-coding
  • 5,994
  • 17
  • 70
  • 99
  • 1
    all the answers posted here are great but using them you lose the cashing option of your pages,since its one controller that will be cached and it will be in the last language you set.is there a solution to this other then using a different controller for every language. –  Feb 04 '10 at 19:57

11 Answers11

95

Have you seen CodeIgniter's Language library?

The Language Class provides functions to retrieve language files and lines of text for purposes of internationalization.

In your CodeIgniter system folder you'll find one called language containing sets of language files. You can create your own language files as needed in order to display error and other messages in other languages.

Language files are typically stored in your system/language directory. Alternately you can create a folder called language inside your application folder and store them there. CodeIgniter will look first in your application/language directory. If the directory does not exist or the specified language is not located there CI will instead look in your global system/language folder.

In your case...

  • you need to create a polish_lang.php and english_lang.php inside application/language/polish
  • then create your keys inside that file (e.g. $lang['hello'] = "Witaj";
  • then load it in your controller like $this->lang->load('polish_lang', 'polish');
  • then fetch the line like $this->lang->line('hello'); Just store the return value of this function in a variable so you can use it in your view.

Repeat the steps for the english language and all other languages you need.

Community
  • 1
  • 1
Randell
  • 6,112
  • 6
  • 45
  • 70
  • thanks for quick answer, yes I have seen this. but it is not clear actually :/ about how to make my need, where to create lang files, what format, what kind of structure, how to call, etc... I'm pretty new at codeigniter. thats why I was looking for clear tutorial or sth. :/ – designer-trying-coding Aug 25 '09 at 13:58
  • 1
    heyooo it is great, working well :D thanks a lot for help! lifesaver you are! :) thanks – designer-trying-coding Aug 26 '09 at 07:45
  • 2
    This is the solution for non-editable text, but it doesn't cover any multilanguage content stored and retrieved from a database. A multilanguage site with a custom content management system made with CI will need more than this. I've made my own, with the help of a language segment in the URL and/or a unique alias segment which identifies a sole content in a sole language. I still haven't figured out how to better manage this. That's why I bumped into this thread. – Luis Martin Jan 11 '13 at 14:04
  • @Randell it is working but can you explain detail in how to translate to other language by onclick....i mean is it to store in sessions? how –  Jan 10 '18 at 06:25
  • @Nadh, it's best to post your question on a new thread, so we can keep the discussions concise. – Randell Jan 15 '18 at 06:01
22

Also to add the language to the session, I would define some constants for each language, then make sure you have the session library autoloaded in config/autoload.php, or you load it whenever you need it. Add the users desired language to the session:

$this->session->set_userdata('language', ENGLISH);

Then you can grab it anytime like this:

$language = $this->session->userdata('language');
Matthew Rapati
  • 5,648
  • 4
  • 28
  • 48
  • yes this was my another issue. you already helped me out :D great thganks! I was also thinking to use cookie to remember visitor's lang selection. – designer-trying-coding Aug 26 '09 at 07:45
  • 1
    where should I define these sessions? I think it is not good to define these at controllers for each page. must be a way that I define at a global file and it effects all site. thanks!! – designer-trying-coding Aug 26 '09 at 07:56
  • Somehow, there's a better way to do this. But that's an entirely new question. But this can be done as well just to get you started. – Randell Aug 26 '09 at 08:07
7

In the controller add following lines when you make the cunstructor

i.e, after

parent::Controller();

add below lines

    $this->load->helper('lang_translate');
    $this->lang->load('nl_site', 'nl'); // ('filename', 'directory')

create helper file lang_translate_helper.php with following function and put it in directory system\application\helpers

function label($label, $obj)
{
    $return = $obj->lang->line($label);
    if($return)
        echo $return;
    else
        echo $label;
}

for each of the language, create a directory with language abbrevation like en, nl, fr, etc., under system\application\languages

create language file in above (respective) directory which will contain $lang array holding pairs label=>language_value as given below

nl_site_lang.php

$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';

en_site_lang.php

$lang['welcome'] = 'Welcome';
$lang['hello word'] = 'Hello Word';

you can store multiple files for same language with differently as per the requirement e.g, if you want separate language file for managing backend (administrator section) you can use it in controller as $this->lang->load('nl_admin', 'nl');

nl_admin_lang.php

$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';

and finally to print the label in desired language, access labels as below in view

label('welcome', $this);

OR

label('hello word', $this);

note the space in hello & word you can use it like this way as well :)

whene there is no lable defined in the language file, it will simply print it what you passed to the function label.

YoGo
  • 79
  • 1
  • 3
1

For easier use CI have updated this so you can just use

$this->load->helper('language');

and to translate text

lang('language line');

and if you want to warp it inside label then use optional parameter

lang('language line', 'element id');

This will output

// becomes <label for="form_item_id">language_key</label>

For good reading http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html

Samy Massoud
  • 4,295
  • 2
  • 35
  • 48
1

I've used Wiredesignz's MY_Language class with great success.

I've just published it on github, as I can't seem to find a trace of it anywhere.

https://github.com/meigwilym/CI_Language

My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.

Mei Gwilym
  • 397
  • 5
  • 15
1

I second Randell's answer.

However, one could always integrate a GeoIP such as http://www.maxmind.com/app/php or http://www.ipinfodb.com/. Then you can save the results with the codeigniter session class.

If you want to use the ipinfodb.com api You can add the ip2locationlite.class.php file to your codeigniter application library folder and then create a model function to do whatever geoip logic you need for your application, such as:

function geolocate()
{
    $ipinfodb = new ipinfodb;
    $ipinfodb->setKey('API KEY');

    //Get errors and locations
    $locations = $ipinfodb->getGeoLocation($this->input->ip_address());
    $errors = $ipinfodb->getError();

   //Set geolocation cookie
   if(empty($errors))
   {
       foreach ($locations as $field => $val):
            if($field === 'CountryCode')
            {
                $place = $val;
            }
       endforeach;
   }
   return $place;
}
Ben Mullikin
  • 263
  • 2
  • 6
  • 3
    Detecting the language based on the IP does not work very well. Think about VPNs, travellers, emigrants or simply countries with multiple languages like Canada or China. It is better to use the browsers language. – PiTheNumber Nov 24 '11 at 12:07
0

When managing the actual files, things can get out of sync pretty easily unless you're really vigilant. So we've launched a (beta) free service called String which allows you to keep track of your language files easily, and collaborate with translators.

You can either import existing language files (in PHP array, PHP Define, ini, po or .strings formats) or create your own sections from scratch and add content directly through the system.

String is totally free so please check it out and tell us what you think.

It's actually built on Codeigniter too! Check out the beta at http://mygengo.com/string

user151516
  • 55
  • 1
0

Follow this https://github.com/EllisLab/CodeIgniter/wiki/CodeIgniter-2.1-internationalization-i18n

its simple and clear, also check out the document @ http://ellislab.com/codeigniter/user-guide/libraries/language.html

its way simpler than

Justis Matotoka
  • 809
  • 6
  • 3
0

I am using such code in config.php:

$lang = 'ru'; // this language will be used if there is no any lang information from useragent (for example, from command line, wget, etc...

if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
$tmp_value = $_COOKIE['language'];
if (!empty($tmp_value)) $lang = $tmp_value;
switch ($lang)
{
    case 'ru':
        $config['language'] = 'russian';
        setlocale(LC_ALL,'ru_RU.UTF-8'); 
        break;
        case 'uk':
        $config['language'] = 'ukrainian';
        setlocale(LC_ALL,'uk_UA.UTF-8'); 
                break;
        case 'foo':
        $config['language'] = 'foo';
        setlocale(LC_ALL,'foo_FOO.UTF-8'); 
                break;
        default:
        $config['language'] = 'english';
        setlocale(LC_ALL,'en_US.UTF-8'); 
        break;
}

.... and then i'm using usualy internal mechanizm of CI

o, almost forget! in views i using buttons, which seting cookie 'language' with language, prefered by user.

So, first this code try to detect "preffered language" setted in user`s useragent (browser). Then code try to read cookie 'language'. And finaly - switch sets language for CI-application

-1

Friend, don't worry, if you have any application installed built in codeigniter and you wanna add some language pack just follow these steps:

1. Add language files in folder application/language/arabic (i add arabic lang in sma2 built in ci)

2. Go to the file named setting.php in application/modules/settings/views/setting.php. Here you find the array

<?php /*

 $lang = array (
  'english' => 'English',

  'arabic' => 'Arabic',  // i add this here

  'spanish' => 'Español'

Now save and run the application. It's worked fine.

Onik
  • 19,396
  • 14
  • 68
  • 91
snakehead
  • 11
  • 1
-1

you can make a function like this

function translateTo($language, $word) {  
   define('defaultLang','english');  
   if (isset($lang[$language][$word]) == FALSE)  
      return $lang[$language][$word];  
   else  
      return $lang[defaultLang][$word];  
}
asteri
  • 11,402
  • 13
  • 60
  • 84
thanhquanky
  • 123
  • 1
  • 1
  • 11
  • 6
    This is an example of bad programming, no offense. DON'T define constants in a function. That's why it's called constant, it's value doesn't change, so it will be defined only once. Second, the code `isset($lang[$language][$word]) == FALSE` would be enough just like this `isset($lang[$language][$word])`, because [isset](http://php.net/manual/en/function.isset.php) returns only true and false. And third, when you evaluate if something is false ALWAYS use `===` to verify the [type](http://www.php.net/manual/en/types.comparisons.php). – machineaddict Mar 27 '13 at 14:00