본문 바로가기
  • [성공하는 개발자] - Developer
PHP

[PHP] Multi-Language setup in CodeIgniter

by Sein-JH 2021. 9. 30.
728x90

CodeIgniter의 다국어 설정

게시일 2015년 12월 30일테구하리프에  의해 

국제화라고도 하는 다국어 기능은 최신 웹 응용 프로그램에 필요합니다. 이 자습서에서는 CodeIgniter를 사용하여 여러 언어를 활성화하는 방법에 대해 설명합니다. 사이트를 다국어로 쉽게 만들 수 있습니다.

이것은 편집할 수 없는 텍스트에 대한 솔루션이지만 데이터베이스에서 저장 및 검색된 다국어 콘텐츠는 다루지 않습니다.

1. 구성 기본 언어  파일을 열고  application/config/config.php사이트의 기본 언어를 지정합니다.

$config['language'] = 'english';

 

2. 다국어 파일
만들기 다국어 파일을 만들고 application/language/ 각 언어(예: 영어, 인도네시아어 등)에 대해 별도의 하위 디렉터리가 있는 디렉터리에 해당 파일을 삽입합니다  .
언어 파일 구조는 다음과 같습니다.

  • application/
    • language/
      • english/
        • welcome_lang.php
        • ……
      • indonesian/
        • welcome_lang.php
        • ……
      • chinese/
        • welcome_lang.php
        • ……
      • arabic/
        • welcome_lang.php
        • ……
      • ……

샘플 언어 파일은 아래에 나와 있습니다.
english/welcome_lang.php 파일은 다음과 같이 작성합니다.

<?php
 $lang['welcome_message'] = 'Welcome!';
?>

 

indonesian/welcome_lang.php 파일은 다음과 같이 작성합니다.

<?php
 $lang['welcome_message'] = 'Selamat datang!';
?>

 

chinese/welcome_lang.php 파일은 다음과 같이 작성합니다.

<?php
 $lang['welcome_message'] = '斯拉末大唐!';
?>

 

arabic/welcome_lang.php 파일은 다음과 같이 작성합니다.

<?php
 $lang['welcome_message'] = 'سلامات داتانغ!';
?>

 

3. 언어 파일 로드 하기

컨트롤러의 함수 를 열고 다음 코드를 작성하십시오.

application/controllers/welcome.php__construct()

public function __construct() {
 parent::__construct();
        $this->load->helper('language');
        $this->lang->load('welcome');
}

 

application/config/hooks.php 파일을 열고 후크를 정의하십시오.

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

 

application/hooks/ 디렉토리 LanguageLoader.php 내부의 파일에 LanguageLoader 클래스를 생성 합니다 .

<?php
class LanguageLoader
{
    public function initialize() {
        $ci =& get_instance();
        $ci->load->helper('language');
 
        $site_lang = $ci->session->userdata('site_lang');
        if ($site_lang) {
            $ci->lang->load('message',$ci->session->userdata('site_lang'));
        } else {
            $ci->lang->load('message','english');
        }
    }
}

 

4. 언어 간 전환

application/controllers/ 디렉토리 내부의 파일에 Langswitch 클래스를 생성 langswitch.php합니다.

<?php f ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Langswitch extends CI_Controller
{
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }
 
    public function switchLanguage($language = "") {
     $language =  $this->uri->segment(1,'english');
     $this->session->set_userdata('site_lang', $language);
     redirect(base_url());
    }
}

 

5. 페이지에 핵심 시스템 설정

관련 페이지에 대한 구성 설정이 필요합니다. 

application/core/ 디렉토리 MY_Config.php 내부의 파일에 MY_Config 클래스를 생성 합니다 .

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Config extends CI_Config {

 function site_url($uri = '', $protocol = NULL) 
 { 
  if (is_array($uri))
  {
   $uri = implode('/', $uri);
  }
  
  if (class_exists('CI_Controller'))
  {
   $CI =& get_instance();
   $uri = $CI->lang->localized($uri);   
  }

  return parent::site_url($uri);
 }
  
}

 

그런 다음 언어를 로드하려면 application/core/ 디렉토리 MY_Lang.php 내부 파일에  MY_Lang 클래스를 만듭니다.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Lang extends CI_Lang {

 var $languages = array(
  'en' => 'english',
  'id' => 'indonesian',
  'cn' => 'chinese',
  'sa' => 'arabic'
 );

 var $special = array (
  ""
 );
 
 var $default_uri = ''; 

 function __construct()
 {
  parent::__construct();  
  
  global $CFG;
  global $URI;
  global $RTR;
  
  $segment = $URI->segment(1);
  
  if (isset($this->languages[$segment])) // URI with language -> ok
  {
   $language = $this->languages[$segment];
   $CFG->set_item('language', $language);

  }
  else if($this->is_special($segment)) // special URI -> no redirect
  {
   return;
  }
  else 
  {
   $CFG->set_item('language', $this->languages[$this->default_lang()]);

   header("Location: " . $CFG->site_url($this->localized($this->default_uri)), TRUE, 302);
   exit;
  }
 }
 
 function lang()
 {
  global $CFG;  
  $language = $CFG->item('language');
  
  $lang = array_search($language, $this->languages);
  if ($lang)
  {
   return $lang;
  }
  
  return NULL; // this should not happen
 }
 
 function is_special($uri)
 {
  $exploded = explode('/', $uri);
  if (in_array($exploded[0], $this->special))
  {
   return TRUE;
  }
  if(isset($this->languages[$uri]))
  {
   return TRUE;
  }
  return FALSE;
 }
 
 function switch_uri($lang)
 {
  $CI =& get_instance();

  $uri = $CI->uri->uri_string();
  if ($uri != "")
  {
   $exploded = explode('/', $uri);
   if($exploded[0] == $this->lang())
   {
    $exploded[0] = $lang;
   }
   $uri = implode('/',$exploded);
  }
  return $uri;
 }
 
 function has_language($uri)
 {
  $first_segment = NULL;
  
  $exploded = explode('/', $uri);
  if(isset($exploded[0]))
  {
   if($exploded[0] != '')
   {
    $first_segment = $exploded[0];
   }
   else if(isset($exploded[1]) && $exploded[1] != '')
   {
    $first_segment = $exploded[1];
   }
  }
  
  if($first_segment != NULL)
  {
   return isset($this->languages[$first_segment]);
  }
  
  return FALSE;
 }
 
 function default_lang()
 {
  foreach ($this->languages as $lang => $language)
  {
   return $lang;
  }
 }
 
 function localized($uri)
 {
  if($this->has_language($uri)
    || $this->is_special($uri)
    || preg_match('/(.+)\.[a-zA-Z0-9]{2,4}$/', $uri))
  {
   
  }
  else
  {
   $uri = $this->lang() . '/' . $uri;
  }
  
  return $uri;
 }
 
}

/* End of file */

 

6. 기본 경로 컨트롤러 설정

$route['^en$'] = $route['default_controller'];
$route['^id$'] = $route['default_controller'];
$route['^cn$'] = $route['default_controller'];
$route['^sa$'] = $route['default_controller'];

 

7. 다국어 전환을 위한 링크 정의
그런 다음 사용 가능한 각 언어를 전환하기 위한 링크를 정의해야 합니다.

<a href='<?php echo $base_url; ?>en/welcome'>English</a>
<a href='<?php echo $base_url; ?>id/welcome'>Indonesian</a>
<a href='<?php echo $base_url; ?>cn/welcome'>Chinese</a>
<a href='<?php echo $base_url; ?>sa/welcome'>Arabic</a>

 

8. 텍스트 행 가져오기 

welcome.phpapplication/views/ 디렉토리 내부의 파일에 있는 행 텍스트를 가져옵니다 .

<?php  echo lang('welcome_message'); ?>

 

 

 

https://teguharief.wordpress.com/2015/12/30/multi-language-setup-in-codeigniter/

 

Multi-Language setup in CodeIgniter

The Multi-Language feature, also known as internationalization, is necessary for the modern web application. In this tutorial, we will discuss how we can enable multiple languages using CodeIgniter…

teguharief.wordpress.com

 

'PHP' 카테고리의 다른 글

[PHP]유튜브 자동 무한 제생  (0) 2021.12.09
[PHP] CodeIgniter 언어 클래스 - 다국어  (0) 2021.09.30
[PHP] Nginx 설치  (0) 2021.09.30
[PHP] Mailer로 메일 전송  (0) 2021.09.30
[PHP] alert 창 띄우기  (0) 2021.09.29

댓글