gettextで他言語対応 | php
index.phpに以下のように
<?php echo _('Here is top page.'); ?>
xgettext index.php –from-code=utf-8 -o messages.pot
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2011-12-11 18:13+0900\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" #: index.php:3 msgid "Here is top page." msgstr ""
先ほど生成された、messages.pot テンプレートから以下のディレクトリ以下にそれぞれ置きます。
$ mkdir -p data/locale/en_US/LC_MESSAGES
$ mkdir -p data/locale/ja_JP/LC_MESSAGES
ja_JP以下に置くmessages.poは CHARSETとmsgstr部を修正した物です。
"Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: index.php:3 msgid "Here is top page." msgstr "トップページです。"
MOを作成。それぞれのmessages.poに対して
[ LC_MESSAGES ]$ msgfmt messages.po
messages.mo
が作成されました。
$ tree -L 4 . `-- locale |-- en_US | `-- LC_MESSAGES | |-- messages.mo | `-- messages.po `-- ja_JP `-- LC_MESSAGES |-- messages.mo `-- messages.po
index.phpで表示前の処理
$language = mb_substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2); $locale = 'en_US'; switch($language){ case 'en': $locale = 'en_US'; break; case 'ja': $locale = 'ja_JP.UTF-8'; // .UTF-8が必要。 break; default: $locale = 'en_US'; } // Set locale and default domain. putenv("LANG=$locale"); setlocale('LC_ALL', $locale); $domain = 'messages'; bindtextdomain($domain, $this->gettext_dir); textdomain($domain);
これでindex.phpの表示が日本語と英語で分けられるようになりました!