2007年10月26日 星期五

PHP用gettext functions 實作i18n

PHPgettext functions 實作 NLS (Native Language Support) i18n多語系轉換

環境:

WinXP SP2, apache_2.0.55-win32, php-5.0.5-Win32

資源參考:

http://php-flp.sourceforge.net/getting_started_english.htm http://www.gnu.org/software/gettext/gettext.html http://tw2.php.net/gettext http://jedi.org/blog/archives/004297.html http://www.rsywx.net/wordpress/?p=184 http://mel.melaxis.com/devblog/2005/08/06/localizing-php-web-sites-using-gettext/ http://hi.baidu.com/momoca/blog/item/e3f63bc7574388dfd10060df.html

(1) 要在PHP裡面使用gettext是需要確定你有這個function extension如果你的php套件已經有包括這個extension的話,在php.ini設定檔內,把 ;extension=php_gettext.dll」前面的分號去掉並存檔後重開apache,代表php開啟這個函式庫支援。並以phpinfo()函式查看是否已經enable這個功能支援。

(2) 鍵入php code存成i18.php進行測試

,若沒開啟php_gettext.dll就會產生Fatal error: Call to undefined function _()

(1) web server的根目錄之下,例如我們在apache/htdoc下的建立根網站名為i18n_test則目錄結構可以為:

i18n_test\locale\zh_TW\LC_MESSAGES\po檔與mo

*po (prtable object)檔編碼與utf-8 mo (machine object)binary格式文件

上面的意思是指在你的網站根目錄底下建立locale的資料夾,locale下面的zh_TW是放你欲轉成的語言,要成繁中就zh_TW,繁簡就zh_CN,英文就en_US,而LC_MESSAGES是約定熟成的,.PO檔所編譯好的.MO檔是作為翻譯用,是實作i18n的主角,.MO檔的作用就類似語言轉換的INDEX檔,編寫PO檔有個好工具就是poEdit,以下就是poEdit如何操作產生po檔。

  • Create a new catalog (File -> new catalog). Choose the language you want to translate the application to. I'm going to use Chinese, The last option (plural forms) is an advanced feature of gettext, just leave it blank

  • set the base path to the directory containing your test php file, and add "." as a path.至於另一個keywords的標籤是當作scan網頁用的識別字。按ok存成檔名為df2zhtw.po路徑存在i18n_test\locale\zh_TW\LC_MESSAGES\df2zhtw.po。接著poEdit will now automatically scan all source files inside the path you specified earlier and extract all strings that are passed to gettext() or _() (or any other methods you may have added in the keywords tab).

  • poEdit會將你指定在base path裡面的所有放在gettext() or _()內的引數都掃瞄到,並且在畫面左列original string內列表出來,接著點選list內的string在畫面下方填入對應文字,完成後就會有畫面左邊original string對應右邊translation的完整mapping index列表,將檔案存起來,則df2zhtw.mo會在同一目錄中自動被compile出來(勾選File>Preference>Editor>Automatically compile .mo file on save)

上述的動作都是完成i18n的前置動作,包括enable gettext function與建立po對應檔,並compile成實際作用的mo檔。現在就開始寫碼!!

< ?

$locale = "zh_TW"; if (isset($_GET["locale"])) $locale = $_GET["locale"]; putenv("LC_ALL=$locale"); setlocale(LC_ALL, $locale); bindtextdomain("df2zhtw", "./locale"); bind_textdomain_codeset("df2zhtw ", 'UTF-8'); textdomain("df2zhtw");

?>

將上述的碼,存成local.php,並在前面的i18.php加入

require_once("local.php");

即完成靜態頁面的i18n實作

bind_textdomain_codeset("df2zhtw ", 'UTF-8'); //最重要的一句

由於po檔我們都是以utf-8來編碼,所以網頁的編碼也以utf-8編碼才不致有中文亂碼的出現,因此必需以bind_textdomain_codeset() 來指定編碼格式。

沒有留言:

張貼留言