PHP support for native language (reprint)

Source: Internet
Author: User
Tags functions gettext header variables php class php file php code variable
Native Language Support
PHP is a great language for developing dynamic Web sites. Some do it for fun while others for business. It is true to a great part of the web was in Chinese Version.. However, if you are targeting a worldwide audience, then neither 中文版 nor Esperanto is a option.

If you are need to deliver the content in several languages, it's a good idea to explore several. However, some alternatives may is suitable for dynamic websites. Added to that, there are the overhead of time spent in maintenance. To further complicate things, your needs may is totally in line with the resources for your have at your disposal. Therefore, it is advisable to choose a alternative that suits your best.

I found myself in positions which required me to deliver content in both 中文版 and Spanish, and in one project a third L Anguage. Here are the possibilities I explored:

Explicit links for each language
Use Apache ' s mod_negotiation
Use the GNU Gettext support in PHP
Write your own
This is article gives a brief introduction to the the ' the ' ' three possibilities, but then we'll go about the fourth solution WH Ich suited the requirements best, given the set of constraints. I am assuming that the reader are at least familiar with PHP programming and the PHP classes.

Principles of content negotiation
Before we go to exploring the various options, we should understand the basics of content negotiation and how that appli ES to the development framework. Then, you are able to develop a Web application which can deliver its content in the language of choice of your visitor .

By simply configuring the Web browser, the user can set it up in a way this his or her preferred language be used when AVA Ilable. Several languages can be specified in a prioritized list with setting up the preferences or option of the browser.

ANDs this list of preferred languages on every request made to the site. This action is totally transparent to the user, as the information gets sent in the Accept-language header, for example:

Accept-language:bg, ES, en-US, fr

Here we visitor has chosen Bulgarian, US 中文版, Spanish and French in. Notice that can even specify regional variants. The two characters are a language code as specified in an ISO standard. This language the code may is followed by a dash and a region code.

As a example, if the request arrives to a website whose content are entirely in Russian, then the "list is exhausted and th E visitor'll get Russian text whether (s) to likes it or not. Now, assuming the website has both 中文版 and Spanish content (the 2nd and 3rd options), then the visitor'll receive PA Ges in Spanish. Why? Simply because here Spanish had higher and priority to Chinese Version..

Sometimes, the Web server itself can manage the content negotiation, if configured to does so. Otherwise, the request for a particular language is ignored. Alternatively, the application that delivers the content takes the decision of which language it are to use. This is exactly what we do later.

Before going further, I would like to point out of that content negotiation are not just dealing with human languages. For example, it also negotiates the kind of information to the client can take by means of MIME types, but this is beyond the Scope of this article.
Explicit Links
Many multi-lingual websites present the content in various languages, and did by placing a link on the document. There would is one link for each of the supported languages. This is a very simplistic approach and should only being used if you are need to have multi-lingual content, but did not have the Resources of a scripting language or dynamic content.

If A document is moved, or a new language are added or removed from the repertoire, then the webmaster would to edit, Add or remove links in each of the affected documents. This can is quite tedious.

Apache ' s content negotiation
The Apache Web server can manage language-sensitive content delivery by using the information from the content negotiation Headers. Then, the webmaster must provide the static pages for each language and name them properly. For example if the Welcome page was available in Spanish and 中文版, the webmaster would these have files: Welcome.html.en

When the Web server is down configured, it'll deliver the appropriate Web page based on the language code according to T He priority list.

This works perfectly for static pages. However, if you have a dynamic website where a great deal of the pages are generated based on queries, then this approach W Ill not work. Another disadvantage is that for you need to know how to do it and I or may does not have access to the configuration files. My experience is that it is a bit tricky and it did not an offer enough flexibility for my purposes.

An advantage to this is between the browser and the Apache server. You are need only to provide the static content.

GNU Gettext with PHP
This is internationalization tool has been around for some time for C programmers. There is also a variant of used on the other un*x, such as HP. Both are very good and are easy to use.

This is extension has been available in PHP since version 3.0.6 and also in 4.0. The Gettext extension are easy to use, and are good if you are generating your webpages. The only thing is here would is the PHP code that generates the content and a set of message catalogs. Supporting a new language is as easy as generating a new catalog with the translations and dropping the file in the Approp Riate directory. Therefore, assuming you have a PHP application named ' myphp ' and that ' appropriate message catalogs exist and are Insta Lled, then the application would have like this:


/* Initialization of GetText in myphp * *
Putenv ("lang= $language");
Bindtextdomain ("myphp", "./locale");
Textdomain ("myphp");
/* Print Some messages in the native language * *
Echo GetText ("Hello new user");
echo _ ("You have no new messages");


My provider had recently upgraded from PHP 3.0RC5 to a PHP4.0 Beta 2 installation. While PHP4 does have support for the Gettext extension, I provider did not compile the PHP4 module with Gettext support. However, even if they had, moving to another provider without, Gettext would a become major.

Ctnls-national Language Support
Having considered various alternatives, I wrote down a set of requirements for the NLS module:

It had to being simple, and based in PHP
Easy to use
Allow the user the freedom of choosing or mixing NLS methods
As a result, I developed a PHP class this would allow the user to set up a multi-lingual website. With this class, the developer can emulate the Apache approach of one file per language, without reconfiguring Apache. Additionally, it is possible to use a PHP script which generates the output in the appropriate language by means of Catalogs.

A Real life Application The ' this ' is ' on my website ' at Http:// Main page was available in 中文版 (E n), Spanish (es) and Dutch (NL).

Using Ctnls
This class are very easy to use. The application would have something like this in its initialization code:

Include (' ctnls.class.php ');

$nls = new Ctnls;


At this point, the class has detected the choice of languages suggested by the user behind the browser. What happens next depends on which method the application uses to provide content.

For static web pages, the approach are similar to the Apache convention. The name of the webpage comprises three parts:the base name, the language extension (two letter code per ISO standard) d the extension which would typically be ". html". For example a welcome page would:


Notice that each page contains a different language. At this point, your PHP application would serve the "file in" appropriate language, by specifying the whole name without The language Id/code. The Ctnls class inserts the appropriate id/code:


$nls->loadpage ("welcome.html");


Here you can specify any filename this is valid to the PHP virtual () function, which are how loadpage () delivers the Conten T to the browser.

Another way to deliver the content in various languages are by using a message catalogs. In this case, the there is one PHP file for each language. It must be a valid PHP file because the message catalog are nothing more than a collection of PHP constants, each referring to a particular message. The reasons why we use constants and not variables are twofold. The ' message does ' not ' and by definition it is a constant. Second and most important, is-that-in-PHP, constants-are-at-any-place, accessible even-within. Whereas, if we use variables for the messages, we would have to resort to-using a "global" declaration for each message us Ed within a function.

The Catalogdir class variable specifies the location of all message catalogs. It is a absolute path within the server where each application would have its message catalog. The name of each catalog file has three parts:the application ID, the language code and a valid PHP extension Can is include () Ed by Ctnls.

Now, assuming we have a application called "MyApp," we could use the following code at the initialization part:


$nls->loadmessages ("MyApp");


This, as OK as loadpage (), can only is used after you have created a new instance of the Ctnls object. This method expects at least one file, with the default language, in the message catalog. In this case, myapp.en.php, and inside, the it must have valid constant for each message. For example:


Define ("Msg_welcome", "WELCOME to our site");
Define ("msg_redirected", "You are being redirected to our new site");



Define ("Msg_welcome", "Bienvenido a Nuestras paginas");
Define ("msg_redirected", "Esta siendo Redireccionado a Nuestro".
"Nuevo Sitio de web");


Only one of these is loaded, depending on the language priority assigned by the user. Then, somewhere in the PHP application, your can generate output like this:


Echo Msg_welcome. "<br>";
Echo msg_redirected;


Auxiliary functions
The Ctnls class has several auxiliary member functions. These are are not normally used, but can come in handy.

The Setcatalogpath function overrides the path to the catalog directory given the configuration part of the Ctnls class .

Setdefaultlanguage does just that. It sets the code of the language to be tried in case all else fails. This is normally Chinese Version.


This language was checked before any of those found in the user preferences. Upon initialization, it is the same as the "the" the "the" the "the" the "the" user list. Once loadpage () or loadmessages () is invoked, Getlanguageid () would return the ID of the language this was used in deliver ing the content to the browser. It is also useful if the user has stored his/her preference in a cookie.

How it actually works
We have already explained what happens during the content negotiation. The browser sends the user ' s choice of the languages in the Accept-language header. This information was available to any PHP script in the $HTTP _accept_language global variable.

When you create a new instance of the Ctnls object, the constructor function Ctnls () is takes control. In turn, it initializes some internal settings and calls SetLanguage (). This internal member function goes through the "List of languages in $HTTP _accept_language" (delimited by commas) by using Only the language code and stripping the region code. The language code is for selecting the appropriate file. In this process, we convert the list to a array, but preserve the language priority.

When a application invokes either loadpage () or loadmessages (), these methods would call the internal search () function.

The search () member function walks the "language preference array from" to "finish" and "if all" them fail to produce R Esults, it checks for the default language. This function keeps track of which languages it tried, so, two, attempts, does not do on the are same.

The GetFile () member function was called every time the search () function generates a new language candidate. It does this by passing it a base name, a language candidate and optionally a file extension.

By passing the base name, the language code and the file extension in, the GetFile () function generates a list of candidate file names. If we are using loadmessages () and pass it's empty extension name, it produces a list by using all known valid PHP script Extensions by prefixing them and the path to the catalog directory. These PHP extension names are currently ". PhP3" and ". php". If, on the "other hand," we pass the "file extension to" function, then, we reduce the list of candidate file names to one .

GetFile () then continues by walking through the "list of candidate" file names until it finds one that exists. Based on this, we determine the current language and the object reads into that file.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.