search
HomeBackend DevelopmentPHP Tutorial让PHP 多语言 【转】

原文地址:http://www.laruence.com/2009/07/19/1003.html

开发多语言的Web应用是一件非常困难的事,各个国家的字符集的编码方式、货币符号、日期格式、数字格式、文字表现都各不相同.

我们今天用一个简单的实例说明一下在PHP中的getText的用法(getText是一系列的工具和库函数,帮助程序员和翻译人员开发多语言软件的), 从而实现PHP的i18n.

现在, 我们假设要显示一个返回主页的link:

//home.php: $str = 'home';   print {$str} HTML;

下面开启我们多语言的开发之旅:

创建pot文件,pot是Portable Object Template的首字母缩写,与po对应的是mo,mo是Machine Object的首字母缩写。前者意指原始的字符串文件,一般用于给翻译人员去修改的,后者则是与机器相关的,一般是供程序读取。可以手工创建pot文件,也可以通过xgettext从代码中抽取字符串来产生。这里是用xgettext来产生的:

xgettext -a home.php -o home.pot

运行该命令后,我们发现,在当前目录下,产生了一个名home.pot的文件,打开该文件,可以看到:

# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2009-07-23 20:56+0800\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: 8bit\n"   #: home.php:2 msgid "home" msgstr ""

根据pot产生不同语言的po文件,这里我们先产生一个简体中文的po文件:

export LANG=zh_CN.gb2312

msginit -l zh_CN.gb2312 -i home.pot

运行该命令后,我们发现,在当前目录下,产生了一个名zh_CN.po的文件,打开该文件,可以看到:

# Chinese translations for PACKAGE package # PACKAGE 软件包的简体中文翻译. # Copyright (C) 2009 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # , 2009. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2009-07-23 20:56+0800\n" "PO-Revision-Date: 2009-07-23 21:00+0800\n" "Last-Translator: FULL NAME \n" "Language-Team: Chinese\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=GB2312\n" "Content-Transfer-Encoding: 8bit\n"   #: test.php:2 msgid "home" msgstr ""

翻译zh_CN.po里对应的字符串为中文:

# Chinese translations for PACKAGE package # PACKAGE 软件包的简体中文翻译. # Copyright (C) 2009 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # , 2009. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2009-07-23 20:56+0800\n" "PO-Revision-Date: 2009-07-23 21:00+0800\n" "Last-Translator: \n" "Language-Team: Chinese\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=GB2312\n" "Content-Transfer-Encoding: 8bit\n"   #: test.php:2 msgid "home" msgstr "主页"

根据po文件生成mo文件。

msgfmt zh_CN.po -o zh_CN.mo

运行该命令后,我们发现,在当前目录下,产生了一个名zh_CN.mo的文件。它是二进制的,不能用文本编辑器打开。

安装mo文件到特定目录中:

cp -f zh_CN.mo .local/LC_MESSAGES/home.mo

修改程序。

setlocale(LC_ALL, 'zh_CN');   // Specify location of translation tables bindtextdomain("home", ".");   // Choose domain textdomain("home");   // Translation is looking for in ./locale/zh_CN/LC_MESSAGES/home.mo now   $str = gettext('home'); //也可以使用_('home')   print {$str} HTML;

运行这个脚本, 看看, 是不是输出正确的中文了呢?

添加其它语言也很容易,不需要修改程序,只需要像对待中文一样,生成一个mo文件,并安装到系统中对应的目录即可。切换不同的语言仅仅是修改当前的locale就行了。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools