Search code examples
phphtmltranslationgettext

How to correctly write PHP with multilingual elements?


I'm using gettext to write a multilingual php web app.

Whats the best way of actually using gettext, I can use it as a key phrase:

echo (_("main.welcomeText.1"));

Or

echo (_("Welcome to my site, we build great webapps."));

In both ways I use a .po file to translate the request ofcourse.

Whats the better way ?


Solution

  • It depends :):

    • you want better debugging
    • you want accurate translation
    • you want speed of programming
    • you want translator not to depends on developer to translate (impossible because developer do not write proper english... french,indian [include native and non native dev])
    • you want the best of 2 worlds

    The best taught way is main.welcomText.1 because:

    • You will use it in lot of place (maybe) so copy past is easier and less error prone.
    • The key has a number witch is easier to search/sort when errors are throw ie: ...Bad key is error.errorCode.321 instead of "Bad things happened in class xy when using null"
    • The key cover the "meaning/semantics" so you have to push your mind a little bit more in order to structure/define your messages ie: main.hello or greeting.formal or greeting.friendly witch is different to translate (ie: "Hello", "Welcome","Hi")
    • Bonus: You can reduce the amount of translation by structuring keys using always the same key (in an easier way. think of refactoring

    using "Welcome to my site, we build great webapps." make it easier to read and for translator to translate but is less easier to correct/debug especially if it's a lot of time in the code

    So keys are used for debugging, so they should be easier to find where in your code they are.

    EDIT: Provide the base English translation ie:

    main.welcomeText.1:Welcome to my site, we build great webapps.

    This is more work for the developer in short term. But few in large project :)