Search code examples
phpgettextpo

Can't get translation using po files


I've got a translation library in my project and I am trying to show some translations but I cannot seem to get gettext to work.

Current structure looks like this:

Project
   test.php
   translations
      iso-3166-1
         ja.po

So inside Project/translations/iso-3166-1 all the .po files are stored.

In test.php I've got:

<?php

$locale = "ja";
$dir = "translations";

putenv("LANGUAGE=$locale");
bindtextdomain("iso-3166-1", $dir);
textdomain("iso-3166-1");

echo gettext("Australia")."\n";

But no matter what I try it doesn't seem to show me any translation. Using this method shouldn't it be able to look for the translation in the path that I have provided.. I've gone through the docs a few times but I can't seem to find any fix.


Solution

  • The environment variable LANGUAGE can hold a priority list of languages, for example ja:fr:es but you still have to set the environment variable LANG to the primary language, in your case ja.

    But the rest of your setup also looks wrong:

    • There are two directory levels missing. Your locale files should be in translations/ja/LC_MESSAGES.
    • Translations are read from .mo files. You have to compile ja.po into ja.mo with the program msgfmt and(!) install it as translations/ja/LC_MESSAGES/iso-3166-1.mo.
    • You are missing the call to setlocale(LC_ALL, 'ja'). You also don't need to modify environment variables then.

    This tutorial may help you to get started: https://www.codeandweb.com/babeledit/tutorials/translation-with-gettext-and-php