In this tutorial we will implement multilanguage to CodeIgniter.
Site Default Language
Open the application/config/config.php file and specify the site’s default language.
$config['language'] = 'bulgarian'; //Language you want to be default
Language Files
The language files must be named with _lang suffix. For example, if you want to create a file containing site’s message translation then the file name might be message_lang.php.
Insert those files into the application/language/ directory with separate sub-directories for each language (for example, english, bulgarian, etc.).
Within the language file (message_lang.php) you would need to assign each line of text to $lang array.
For example:
– english/messages_lang.php
- bulgarian/messages_lang.php
Loading Language Files
In order to fetch a line from a particular language file, you need to load the language file first.
Into the controller’s __construct() function write the following code.function __construct(){ parent :: __construct(); //Setting language in session on first load if(!$this->session->userdata('site_lang')){ $this->load->library('session'); $newdata = array( 'site_lang' => $this->config->item('language') ); $this->session->set_userdata($newdata); } //Loading language from session variable $this->language = $this->session->userdata['site_lang']; $this->lang->load('messages',$this->language); }Loading language files using hooks is not a good idea, because hooks are loaded before constructors or after controllers and we can't use language files in the controller.
Fetching line of text
After loading the language file you can fetch the line text using the following code.
$this->lang->line('welcome_message');OR you can check the whole language file
print_r($this->lang->language);Switch Different Languages
Now it’s time to switch different languages and make your site multilingual. We will use the session to store user’s requested language and load the respective language.
Before starting to implement multilingual features, open the application/config/autoload.php file and load SESSION library and URL helper.
$autoload['libraries'] = array('session'); $autoload['helper'] = array('url');We will create LanguageSwitcher controller for handing the language switch. application/controllers/LanguageSwitcher.php file contain the following code.
session->set_userdata('site_lang', $language); redirect($_SERVER['HTTP_REFERER']); } }Display the languages dropdown into view. Once the language option is changed, the switchLang() function of LanguageSwitcher controller would be called. switchLang() function set the site language into session based on the requested language and redirected to the view page. The sample languages dropdown and multi-language welcome message code is given below.
lang->line('welcome_message'); ?>
For this tutorial I was using help from http://www.codexworld.com/ and I believe I simplified it a little bit.