Best practice for managing language?

  • Thread starter Thread starter Bes
  • Start date Start date

Bes

Bes

Soldato
Joined
18 Oct 2002
Posts
7,318
Location
Melbourne
Hi

Currently building a site with a lot of interactive elements.

I am wondering how people handle text? Is the best approach to use a database, or flat files, or just insert it directly into the page?

I may want to offer my users multiple languages in the future, so need to bea this in mind.

Thanks
 
Depends on the environment, language and so on. Yes some kind of resource file e.g. XML, or a database. Using a database is infinitely easier to manage over flat files, especially when merging changsets or working with lots of developers.

For example, in PHP you could do something as simple as defining an array of strings and their corresponding (english) translations, and including this by default. For each different language, translate as much of the array as you can in a different file. Then you can simply include another language file when relevant, and have the default language as fallback for any strings not translated.

Code:
// in lang/en.php
$lang['intro-text'] = 'Hello World';
$lang['add-to-cart'] = 'Buy me now!';

// in lang/fr.php
$lang['intro-text'] = 'Bonjour Monde';

PHP:
<?php
include 'lang/en.php';
include 'lang/fr.php';

<div class="helloworld">
  <h2><?=$lang['intro-text']?></h2> // Bonjour Monde
  <p><?=$lang['add-to-cart']?></p> // Buy me now!
</div>
In principle, this is what most people do. But as I say, the storage mechanism and actual implementation depends on the environment.
 
A nice standardized way is to use gettext. Where you would normally just output text you wrap it in a function called _, so instead of <h2>Hello</h2> You would have <h2><?php echo _('Hello'); ?></h2>

Gettext can then scan your source and produce a language file for translation. It will also handle duplicates etc automatically.

Dutch language file example from one of my projects:
Code:
#: ../../../templates/default.php:95
msgid ""
"This will cancel the current download and remove it from the queue, continue?"
msgstr ""
"Dit zal de huidige download annuleren en verwijderen van de wachtrij, "
"doorgaan?"

Gettext language files are fairly universally accepted by professional translation services, so it's a good start.
 
Last edited:
Back
Top Bottom