以往在多國語系的寫法支 援上

通常是寫在程式內,例如 以下此種寫法和設定

$lang = “zh_TW”;

$lang_file = “$lang” . “.php”

Include_once(“./lang/$lang_file”);

 

另外一種方法,則是採用 系統語系檔的支援方式

此種方式比較上一種的方 法,優點是可自動擷取程式內需處理的字串,如程式內使用gettext函數,用系統指令xgettext就可自動產生PO檔^^

 

可以嘗試以下的簡單範 例:

<?php

 //設定locale參數,要換語系在這裡換

putenv('LANG=zh_TW');

setlocale(LC_ALL, 'zh_TW');

 

// 設定gettext

bindtextdomain("test", '/var/www/test/locale');

textdomain("test");

  

echo gettext("hihi!");

echo '<br>';

echo _("you’re welcome");    //_()是gettext的簡寫

echo _("hihi!");        //重複字串試看看程式會如何處理

//echo _("New, line!");    //測試註解會如何處理

?>

 

然後到系統下執行xgettext指令:

 xgettext -d test test.php

 

果然有產生 test.po檔,來看看檔案內的內 容,會自動處理重複字串:

 #: test.php:2 test.php:5

msgid "hihi!"

msgstr ""

 

#: test.php:4

msgid "you’re welcome"

msgstr ""

 

可以一次處理所有的PHP檔案,指令換成xgettext -d test *.php 就可以囉!

接下來就是編輯PO檔的內容到各語系內囉, 例如編輯繁體中文的內容:

 

編輯/etc/lib/locale/zh_TW/LC_MESSAGES/test.po

 

 #: test.php:2 test.php:5

msgid "hihi!"

msgstr "嗨!"

 

#: test.php:4

msgid "you’re welcome"

msgstr "不客氣"

 

產生完PO檔後,要用msgfmt指令將PO檔轉成MO (binary data)才能提供gettext函數使用:

 msgfmt -o /etc/lib/locale/zh_TW/LC_MESSAGES/test.mo  /etc/lib/locale/zh_TW/LC_MESSAGES/test.po

 

 幾個細節注意如下:

  1. PHP檔案內如果gettext包的不只是英文, 需要加 --from-code=encoding,

           xgettext --from-code=UTF-8 –d test test.php

  1. 自動產生的PO檔案內,需將Content-Type: text/plain; charset=CHARSET 設定成UTF-8

 

  1. 如有修改,可用msgmerge指令進行PO合併

 

arrow
arrow
    全站熱搜

    miggo 發表在 痞客邦 留言(0) 人氣()