This entry was posted on Monday, June 25th, 2007 at 12:13 pm and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.
php-developers.net
php and mysql web development services
Create a multilingual site with php and gettext
Creating a multilingual site is a common task that can be simplified to a considerable amount if the right tools are used. One of the common ways to create a website in several languages is by using a set of GNU tools called Gettext. This article deals with the usage of Gettext and solves common multilingual tasks.
Requirements
You must have the Gettext extension enabled in php.ini
Using Gettext
1. Set up the Gettext environment
1.1. Define what language to use (in our case ‘bg’ stands for Bulgarian)
$language = ‘bg’;
1.2. Save it in the LANG environment variable
putenv(”LANG=$language”);
1.3. Set the current locale
setlocale(LC_ALL, $language);
1.4. Set the default domain
textdomain(’messages’);
1.5. Set the path for the domain ‘messages’
bindtextdomain(’messages’, ‘/path/to/locale/directory’);
1.6. Specify the character encoding in which the messages from the DOMAIN message catalog will be returned. For multilingual sites you would most likely use UTF-8
bind_textdomain_codeset(’messages’, ‘UTF-8′);
2. Usage in the php files is as simple as using the gettext function or the _()
echo gettext(”I bought a new car yesterday”);
… is same as …
echo _(”I bought a new car yesterday”);
… and the last step is to create the Gettext files.
3. Set up the Gettext files
3.1. Directory structure - a locale directory is expected where you will keep the files containing the translated strings:
/locale
/bg
/LC_MESSAGES
messages.po
messages.mo
Adding an additional language files would result in creating its own set of directories. For example:
/locale
/bg
/LC_MESSAGES
messages.po
messages.mo
/en
/LC_MESSAGES
messages.po
messages.mo
3.2. The file with the ‘po’ extension holds the human readable strings and their translation. Here is what it contains, broken to parts:
3.2.1. Some header messages that give information about the file and the project:
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR Free Software Foundation, Inc.
# FIRST AUTHOR, YEAR.
#
#, fuzzy
msgid “”
msgstr “”
“Project-Id-Version: PACKAGE VERSION\n”
“POT-Creation-Date: 2002-04-06 21:44-0500\n”
“PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n”
“Last-Translator: FULL NAME \n”
“Language-Team: LANGUAGE \n”
“MIME-Version: 1.0\n”
“Content-Type: text/plain; charset=CHARSET\n”
“Content-Transfer-Encoding: ENCODING\n”
3.2.2. The strings and their translation
For the messages.po file in the ‘bg’ directory
#: products.php:3
msgid “I bought a new car yesterday”
msgstr “Купих си нова кола вчера”
For the messages.po file in the ‘en’ directory
#: products.php:3
msgid “I bought a new car yesterday”
msgstr “I bought a new car yesterday”
Here are the explanations of these lines:
#: products.php:3 -> shows the file and the line number that contains the string
msgid “I bought a new car yesterday” -> this is the string to be translated
msgstr “Купих си нова кола вчера” -> this is the translation of the string
3.3. The file with the ‘mo’ extension is the binary format. We will talk about the generation of this file later on in this article.
4. Creating po files
Obviously adding by hand the strings to be translated is not very convenient. Gettext offers a convenient way to automatically extract the Gettext strings from the php files using the xgettext command
$ xgettext -n *.php
This would create a po file with the headers explained above and includes the strings to be translated.
5. Translate the strings in the po files. Convenient tools for doing this are:
For Linux - KBabel
For Windows - poEdit
6. Converting po files to mo files
Once you translated the files you need to turn them to binary files (’mo’ files) and copy them to the appropriate language directories. To do the conversion run the following command:
$ msgfmt messages.po
7. What do we do if you need to add some more strings to the pot files and if we need to update some strings? The most logical way is to merge the current pot file with the new pot file that contains the new strings. To do this in Gettext use the msgmerge command.
$ msgmerge products1.po products2.po –output-file=merged_products.po
8. Advanced usage of gettext
8.1. Using dynamic variables. What about if you want to use dynamic variables within the translated strings? The printf function comes in hand.
printf(gettext(”Hello, %s”), “Peter”);
And the po file will look like this:
#: products.php:7
msgid “Hello, %s”
msgstr “Здравей, %s”
8.2. Another issue is the plural version of the strings. Printf comes in hand again together with ngettext:
printf(ngettext(”%d car”, “%d cars”, 1), 1);
printf(ngettext(”%d car”, “%d cars”, 2), 2);
And the po file will look like this:
msgid “%d car”
msgid_plural “%d cars”
msgstr[0] “%d кола”
msgstr[1] “%d коли”
An important factor here is to add a header in the po file that defines the plural format for the specified language. The following example is specific to the English language. For other languages check the Gettext documentation:
“Plural-Forms: nplurals=2; plural=n != 1;\n”
Examples - source code
Here is an example from a shopping cart application with fully functioning Gettext examples. To install and run it just unzip it to a subdirectory in htdocs and run items.php.
Click here to download the attachmentColorado bad credit mortgage
Consolidation credit debt loan poor
Free trans union annual credit report
Instant approved credit card
Citibank credit card india
Bad credit home mobile mortgage
Bad credit home loan missouri
Debt consolidation uk
Personal secured consolidation loan uk
Low fixed apr credit card
Car loan bad credit history
Fargo loan student well
Average debt loan student
Payday loan no faxing cheap
Credit repair program
Instant credit card offer
Free uk online credit report
Compare business credit card
Bad credit home loan refinance
Home improvement loan uk
Country wide home loan
Ways to increase your credit score
Free annual credit report with experian
Chase credit card service
Hsbc rs credit card
Federal government loan student
Bad credit fast cash loan
Bad credit credit card approval
Bad credit personal loan company
Equifax credit report trans union
Free annual credit report with equifax
New york home loan
3 credit score
Consolidation debt loan uk unsecured
Best debt consolidation
Equity home loan minnesota rate
Small personal loan bad credit
Bad credit computer
Pennsylvania home equity loan
Online debt consolidation program
Worst credit card company
American express prepaid credit card
Bad credit gas card
Home equity mortgage loan
No telecheck payday loan
Broward home loan
Credit repair info
Bad credit easy personnel loan
Citibank student loan
Acs loan student
Credit score rating chart
Credit repair company
College student in credit card debt
Debt consolidation loan for non home owner
Free online credit report without credit card
Equifax free online credit report
Debt consolidation loan for home owner
Credit card account online
Payday loan in canada
Airline miles reward credit card
Student loan consolidation loan
Advance cash fast loan payday
Georgia mortgage home loan
Free debt consolidation
Manufactured home refinance loan
First time mortgage bad credit
Canada consolidation debt loan loan student
Bad consolidation credit loan student
Very bad credit auto loan
Student loan consolidation rate
Auto financing bad credit
Broker consolidation debt lead mortgage
Credit card processing canada
Government of canada student loan
Free 3 bureau credit report
Va home loan certificate
Bad credit card application
Free credit repair form
Consolidation government loan student
List credit card company
Credit card merchant account program
Credit card consolidation help
Find out my credit score for free
California second mortgage home loan
Georgia debt consolidation loan
Bad credit home loan mortgage services
Bad credit student personal loan
Advance cash loan military payday
Get credit card numbers
Free payday loan
Free credit report credit card
Instant personal loan
Bad credit mortgage uk
Compare credit card reward
Bad construction credit home loan
Florida free debt consolidation loan
Bank of america personal loan
Good credit score
Credit repair debt consolidation
Accept credit card on the web
Bad credit education loan
Loan mae sallie student
Federal student loan interest rate
Bad credit home homeequity1.us loan mortgage
Equity home loan mortgage second xxasdf
Alaska loan student
Adjustable rate home loan
Debt consolidation mortgage refinance
24 hour payday loan
Buying a home with bad credit
Loan mae sallie services student
First time home loan bad credit
Bad credit government loan mortgage
Shell credit card company
Fast bad credit loan
Illinois payday loan
Add consolidation debt link
Georgia home improvement loan
678 average credit score us
Free porn no credit card check
Beacon credit score
Computer financing bad credit
Home equity loan refinancing
Bad credit cell phone
Nevada payday loan
Loan mortgage home equity real estate
Free annual credit report law
Michigan debt consolidation loan
Bad credit down home loan money no
Credit repair kit
Federal home loan bank of new york
Bad credit home loan mortgage refinance
Delta airline credit card
Credit repair lawyer
Best free debt consolidation service
On line home equity loan
California home loan mortgage second southern
Countrywide customer home loan service
Raise credit score
Federal home improvement loan
Payday loan personal
Bankruptcy equity home loan
Check credit report
Bad credit no credit car loan
Cfs loan student
Home interest loan mortgage only
Debt consolidation
Countrywide home equity loan
Online payday loan no faxing
Government student loan