Book HomePHP CookbookSearch this book

16.5. Localizing Text Messages

16.5.1. Problem

You want to display text messages in a locale-appropriate language.

16.5.2. Solution

Maintain a message catalog of words and phrases and retrieve the appropriate string from the message catalog before printing it. Here's a simple message catalog with some foods in American and British English and a function to retrieve words from the catalog:

$messages = array ('en_US' => 
             array(
              'My favorite foods are' => 'My favorite foods are',
              'french fries' => 'french fries',
              'biscuit'      => 'biscuit',
              'candy'        => 'candy',
              'potato chips' => 'potato chips',
              'cookie'       => 'cookie',
              'corn'         => 'corn',
              'eggplant'     => 'eggplant'
             ),
           'en_GB' => 
             array(
              'My favorite foods are' => 'My favourite foods are',
              'french fries' => 'chips',
              'biscuit'      => 'scone',
              'candy'        => 'sweets',
              'potato chips' => 'crisps',
              'cookie'       => 'biscuit',
              'corn'         => 'maize',
              'eggplant'     => 'aubergine'
             )
            );

function msg($s) {
  global $LANG;
  global $messages;
  if (isset($messages[$LANG][$s])) {
    return $messages[$LANG][$s];
  } else {
    error_log("l10n error: LANG: $lang, message: '$s'");
  }
}

16.5.3. Discussion

This short program uses the message catalog to print out a list of foods:

$LANG = 'en_GB';
print msg('My favorite foods are').":\n";
print msg('french fries')."\n";
print msg('potato chips')."\n";
print msg('corn')."\n";
print msg('candy')."\n";
My favourite foods are:
chips
crisps
maize
sweets

To have the program output in American English instead of British English, just set $LANG to en_US.

You can combine the msg( ) message retrieval function with sprintf( ) to store phrases that require values to be substituted into them. For example, consider the English sentence "I am 12 years old." In Spanish, the corresponding phrase is "Tengo 12 años." The Spanish phrase can't be built by stitching together translations of "I am," the numeral 12, and "years old." Instead, store them in the message catalogs as sprintf( )-style format strings:

$messages = array ('en_US' => array('I am X years old.' => 'I am %d years old.'),
                   'es_US' => array('I am X years old.' => 'Tengo %d años.')
            );

You can then pass the results of msg( ) to sprintf( ) as a format string:

$LANG = 'es_US';
print sprintf(msg('I am X years old.'),12);
Tengo 12 años.

For phrases that require the substituted values to be in a different order in different language, sprintf( ) supports changing the order of the arguments:

$messages = array ('en_US' => 
                    array('I am X years and Y months old.' => 
                          'I am %d years and %d months old.'),
                   'es_US' =>
                    array('I am X years and Y months old.' => 
                          'Tengo %2$d meses y %1$d años.')
            );

With either language, call sprintf( ) with the same order of arguments (i.e., first years, then months):

$LANG = 'es_US';
print sprintf(msg('I am X years and Y months old.'),12,7);
Tengo 7 meses y 12 años.

In the format string, %2$ tells sprintf( ) to use the second argument, and %1$ tells it to use the first.

These phrases can also be stored as a function's return value instead of as a string in an array. Storing the phrases as functions removes the need to use sprintf( ). Functions that return a sentence look like this:

// English version
function i_am_X_years_old($age) {
 return "I am $age years old.";
}

// Spanish version
function i_am_X_years_old($age) {
 return "Tengo $age años.";
}

If some parts of the message catalog belong in an array, and some parts belong in functions, an object is a helpful container for a language's message catalog. A base object and two simple message catalogs look like this:

class pc_MC_Base {
  var $messages;
  var $lang;

  function msg($s) {
    if (isset($this->messages[$s])) {
      return $this->messages[$s];
    } else {
      error_log("l10n error: LANG: $this->lang, message: '$s'");
    }
  }

}

class pc_MC_es_US extends pc_MC_Base {

  function pc_MC_es_US() {
    $this->lang = 'es_US';
    $this->messages = array ('chicken' => 'pollo',
                 'cow'     => 'vaca',
                 'horse'   => 'caballo'
                 );
  }
   
  function i_am_X_years_old($age) {
    return "Tengo $age años";
  }
}

class pc_MC_en_US extends pc_MC_Base {
  
  function pc_MC_en_US() {
    $this->lang = 'en_US';
    $this->messages = array ('chicken' => 'chicken',
                 'cow'     => 'cow',
                 'horse'   => 'horse'
                 );
  }
   
  function i_am_X_years_old($age) {
    return "I am $age years old.";
  }
}

Each message catalog object extends the pc_MC_Base class to get the msg( ) method, and then defines its own messages (in its constructor) and its own functions that return phrases. Here's how to print text in Spanish:

$MC = new pc_MC_es_US;

print $MC->msg('cow');
print $MC->i_am_X_years_old(15);

To print the same text in English, $MC just needs to be instantiated as a pc_MC_en_US object instead of a pc_MC_es_US object. The rest of the code remains unchanged.

16.5.4. See Also

The introduction to Chapter 7 discusses object inheritance; documentation on sprintf( ) at http://www.php.net/sprintf.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.