Localizing strings with gettext

suggest change

GNU gettext is an extension within PHP that must be included at the php.ini:

extension=php_gettext.dll #Windowsextension=gettext.so #Linux

The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications.


Translating strings can be done in PHP by setting the locale, setting up your translation tables and calling gettext() on any string you want to translate.

<?php
// Set language to French
putenv('LC_ALL=    fr_FR');
setlocale(LC_ALL, 'fr_FR');

// Specify location of translation tables for 'myPHPApp' domain
bindtextdomain("myPHPApp", "./locale");

// Select 'myPHPApp' domain
textdomain("myPHPApp");

myPHPApp.po

#: /Hello_world.php:56
msgid "Hello"
msgstr "Bonjour"

#: /Hello_world.php:242
msgid "How are you?"
msgstr "Comment allez-vous?"

gettext() loads a given post-complied .po file, a .mo. which maps your to-be translated strings as above.

After this small bit of setup code, translations will now be looked for in the following file:

Whenever you call gettext('some string'), if 'some string' has been translated in the .mo file, the translation will be returned. Otherwise, 'some string' will be returned untranslated.

// Print the translated version of 'Welcome to My PHP Application'
echo gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
echo _("Have a nice day");

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Localization:
* Localizing strings with gettext

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
50 Localization
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR