16.4. Localizing Text Messages
Problem
You want to display text messages in a locale-appropriate language.
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'"); } }
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( ) ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.