PHP - Multilingual site

From XennisWiki
Jump to: navigation, search

To create a website with multiple languages a easy way is to use the in PHP integrated solution for this problem by using the function gettext and language files.

Use gettext and languages files

Getting started

Further informations: PHP manuel - gettext

Setup language

$language = 'en';
$locale = 'en_GB';
/* Set language and locale */
setlocale(LC_ALL, $locale.'UTF-8');

/* Specify location of translation files and choose domain
 * e.g. ./locale/de_DE/LC_MESSAGES/
 *      ./locale/en_GB/LC_MESSAGES/
 *          ^                         ^
 *          |                         |
 *      second parameter        first parameter
bindtextdomain('messages', './locale');
bind_textdomain_codeset('messages', 'UTF-8');


// Print message
echo gettext('Hello World');
// Use the short alias for gettext()
echo _('Hello World');

Create language files

The program Poedit is really helpful to create and handle the languages files (e.g.

Open the program

  • File > New catalog
    • Tab Translations properties: Write under language e.g. German, GERMANY and choose for Charset and Source code charset UTF-8 as encoding.
    • Tab Sources paths: Select as Base path the root folder of your website. Add under Paths a new item with an dot (.) as content.

Save user language using sessions

// Start session to save language
// Get language, e.g. mySite.php?lang=de
if ( isset($_GET['lang']) ) {
    $_SESSION['lang'] = $_GET['lang'];

if ($_SESSION['lang'] === 'en') {
    $locale = 'en_GB';    
elseif ($_SESSION['lang'] === 'de') {
    $locale = 'de_DE';    

// Code from "Getting started"

External links