php Xiaobian Banana teaches you how to build a multilingual website with PHP, allowing you to easily eliminate language barriers. With simple settings and techniques, you can add multiple language options to your website to provide a more friendly access experience for users in different regions. Make your website more attractive and international!
Create a new table for multilingual data, including the following fields:
CREATE TABLE translations ( id INT NOT NULL AUTO_INCREMENT, locale VARCHAR(255) NOT NULL, key VARCHAR(255) NOT NULL, value TEXT NOT NULL, PRIMARY KEY (id) );
2. Set language switching mechanism
Add a language switcher to the top or sidebar of your website to allow users to select their preferred language.
// 获取当前语言 $current_locale = isset($_GET["locale"]) ? $_GET["locale"] : "en"; // 语言链接 $languages = array("en", "es", "fr"); foreach ($languages as $lang) { echo "<a href="?locale=$lang">$lang</a> "; }
3. Load translation
Load translations for the current language from the database.
// 查询翻译 $translations = $db->prepare("SELECT * FROM translations WHERE locale = ?"); $translations->execute(array($current_locale)); // 存储翻译数组 $tr = array(); foreach ($translations as $row) { $tr[$row["key"]] = $row["value"]; }
4. Show translation
In your html code, use the gettext
function to get the text from the translation array.
// 使用 gettext 获取翻译 echo gettext("This is a test");
5. International date and time
For date and time display, use PHP’s Intl
extension:
// 创建 DateTime 对象 $dt = new DateTime(); // 国际化日期和时间格式 $dt->setTimezone(new DateTimeZone("Europe/London")); echo $dt->fORMat("Y-m-d H:i:s");
6. Localized numbers and currencies
Likewise, for number and currency formatting, use the Intl
extension:
// 创建 NumberFormatter 对象 $formatter = new NumberFormatter("en_US", NumberFormatter::CURRENCY); // 格式化货币 $amount = 1000; echo $formatter->formatCurrency($amount, "USD");
7. Keep the code clean
To keep your code clean, you can create functions and helpers to simplify the process of translation and internationalization. For example:
function t($key) { global $tr; return isset($tr[$key]) ? $tr[$key] : $key; }
Conclusion
Building a multilingual website using php eliminates language barriers and makes your website accessible to a global audience. By following the steps in this article and using the provided sample code, you can easily create and manage a multilingual website.
The above is the detailed content of Building Multilingual Websites with PHP: Eliminating Language Barriers. For more information, please follow other related articles on the PHP Chinese website!