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の表示が日本語と英語で分けられるようになりました!

This entry was posted on 日曜日, 12月 11th, 2011 at 6:52 PM and is filed under blog, gettext 他言語対応, zend. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Unityによるゲームを公開しております iOS/Android
https://itunes.apple.com/jp/app/lost-knight-3d-action/id900917032
https://play.google.com/store/apps/details?id=com.groundroad.runknight

各種開発支援・機能開発等小さいお仕事などもお請けしております。
unity開発支援, PHPシステム開発, javascript/html5 フロント開発, titanium mobileアプリ開発
お気軽にお問い合わせください
大崎・五反田近郊での対面でのお打ち合わせはいつでも可能です。