Home » Php » How to create multilingual web application in Codeigniter PHP?

How to create multilingual web application in Codeigniter PHP?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to create multilingual web application in Codeigniter PHP. I want to know is there any language pack available in Codeigniter or I need to create language folders with files including variables in it.
Can you please let me know how to do it in Codeigniter?

How to&Answers:

to create a multilingual site you have to
1 = by in the codeigniter folder
<< application / language >> you will create two folders for example french and english
after in each folder you will create a file that will not be called example content_lang.php
for each file for example french
you will have <>

<?php return [ "welcome"=>"Bienvenue",];

and for each file for example English
you will have >

<?php return [ "welcome"=>"Welcome",];

then you have to create a lang.php file in the hooks “application / hooks”
in the lang.php file

<?php  /*** classe hook for loading languages*/
class lang{
public function __construct(){
    $this->ci =& get_instance();
    $this->ci->load->helper('language'); 
    $this->ci->load->library('session');       
    $this->ci->config->load('lang');
    $this->lang_map  = $this->ci->config->item("lang_map");
}
private function get_current_lang(){
    return $this->ci->input->get('lang') ?? $this->ci->session->userdata('site_lang');
}
public function initialize() {
    @$browser_lang = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
    $browser_lang = strtolower(substr(chop($browser_lang[0]),0,2));
    array_key_exists($browser_lang,$this->lang_map)?($lang_to_load = $this->lang_map[$browser_lang]):($lang_to_load = "english");
    $this->ci->session->set_userdata('site_lang',$browser_lang);
    $this->ci->lang->load('content',$lang_to_load);
    return;
}
public function load_lang(){
    $site_lang = $this->get_current_lang();
    if ($site_lang AND array_key_exists($site_lang,$this->lang_map)) {
        $this->ci->lang->load('content',$this->lang_map[$site_lang]);
    } else {
        $this->initialize();
    }

}
}

then you will create a helper langue_helper.php in “application / Helper”
in this file you will put

<?php  
if (!function_exists("_l")) {
    /**
     * function which allows to load a message according to the language
     * @param  string $message message to display
     * @return string          messaging in the current language
     */
    function _l($message,$args=[],$lang=null){
        $current_lang = get_current_lang(); 
        $ci =& get_instance(); 
        $keys = array_keys($args);
        $dataset = [];

        if (!is_null($lang)) {
            $lang_map  = $ci->config->item("lang_map");
            $ci->lang->load('content',$lang_map[$lang]);
        }
        foreach ($keys as $key) {
            $dataset[":".$key] = $args[$key];
        }
        $content = $ci->lang->line($message);
        if(empty($content)){
            $content = $message;
        }
        if (!is_null($lang)) {
            $lang_map  = $ci->config->item("lang_map");
            $ci->lang->load('content',$lang_map[$current_lang]);
        }
        return  str_replace(array_keys($dataset), array_values($dataset), $content);
    }
}
if (!function_exists("get_lang")) {
    /**
     * function which allows to load a message according to the language
     * @param  string $message message a afficher
     * @return string          messsage dans la langue actuelle
     */
    function get_lang(){
        $ci =& get_instance(); 
        $lang = $ci->input->get("lang")??$ci->session->userdata("site_lang");
        $lang = strtolower($lang);
        switch ($lang) {
            case "en":
                return "FR";
                break;
            case "fr":
                return "EN";
                break;

            default:
                return "EN";
                break;
        };
    }
}if (!function_exists("get_lang_url")) {
/**
 * function to retrieve the url according to a language
 * @param  string $message message to display
 * @return string          messaging in the current language
 */
function lang_url($lang=null,$trailing = false){
    if ($lang === null) {
        $lang = get_lang();
    }
    $ci =& get_instance(); 
    $ci->config->item("lang_map");
    $lang = strtolower($lang);
    if(!array_key_exists($lang,$ci->config->item("lang_map"))){
        $lang = $ci->config->item("default_lang");
    }
    return current_url()."?lang=$lang";
}

}
then you will modify the hooks.php in “application / config / hooks.php”
you will put this

$hook['post_controller_constructor'][] = array(
    'class' => 'lang',
    'filename' => 'lang.php',
    'filepath' => 'hooks',
    'function' => 'initialize',
);
$hook['post_controller_constructor'][] = array(
    'class' => 'lang',
    'function' => 'load_lang',
    'filename' => 'lang.php',
    'filepath' => 'hooks'
);

finally you will create a Lang.php controller in “application / controller”

<?php defined('BASEPATH') OR exit('No direct script access allowed');
 class Lang extends CI_Controller {
  private $support_lang;
  public function __construct()
  {
     parent::__construct();
     $this->support_lang = array("french","english");
  }
public function change_lang($lang=""){
        if ($lang != "" AND in_array($lang,$this->support_lang)) {
           $array = array(
              'site_lang' => $lang
           );
           $this->session->set_userdata( $array );
        }else{
           $array = array(
              'site_lang' => 'english'
           );
           $this->session->set_userdata( $array );
        }
        redirect($_SERVER["HTTP_REFERER"]);
     }
    }

in the views to display the text you will do

<?= _l('welcome')?> or <?php echo _l('welcome')?>

to change the language

<a href="<?= lang_url() ?>" > <?= get_lang() ?></a>