简体   繁体   中英

How do I store and retrieve language specific text in PHP?

I'm currently in the process of building a web application which will be used by people in different countries

Currently all the messages that I output (ie errors etc) are in English.

What is the best way to store language constants and retrieve them?

It's quite likely that the messages may need bits of information injected into them too like data the user entered etc,

For example we might have the error:

The email address 'test@test.co' was not a valid email address.

GNU gettext provides tools and a framework for doing this. This is a decent article about using gettext in PHP.

The usual approach for injected info is using printf() codes, normally %s:

The email address '%s' was not a valid email address.

Beyond that, you have a number of options:

  • The gettext functions allow you to use specific tools to build the initial string files and keep track of translation status

  • Good old PHP constants are very handy if you only have a few strings to translate

Also, don't forget that localization does not merely consist on translating text. You also have to take into account stuff like:

  • Date and numeric formats
  • Plural / Singular forms
  • Alphabetical order

I'd store them in database and retrieve by language. For example,

SELECT message FROM messages WHERE key = 'error_email' AND lang = 'de';

Just a very generic idea off the top of my head

It probably makes sense to store languages in a different table and use foreign keys.

Have you looked into XLIFF ? I think this article is particularly informative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM