basteyy/php-i18n

PHP的简单I18N功能

1.0.2 2024-05-20 19:59 UTC

This package is auto-updated.

Last update: 2024-09-20 20:47:27 UTC


README

作为一个老牌的CakePHP用户,我最初使用了__()函数。我喜欢这种适用于小型项目的方法,并为自己的项目创建了这个小型的包。

你在代码中某处使用了__()。只要你不创建翻译,参数(字符串)将被返回。如果你创建了一个翻译,将返回翻译。

安装

composer require basteyy/php-i18n

使用方法

语言文件是ini格式。为了支持字符串的所有变体,键使用xxh3算法进行哈希(这是目前PHP中最快的算法)。

; Content of /var/www/lang/de_DE.ini

; Original: Add 
2519a9e8bc4544e5 = "Hinzufügen"

; Original: Remove
d93080c2fe513df2 = "Entfernen"

; Original: Remove %s Items
4937f99272d45d21 = "%s Dinge entfernen"
// Content of /var/www/index.php

use basteyy\I18n\I18n;

I18n::addTranslationFolder(__DIR__ . '/lang/');
I18n::addTranslationFolder(__DIR__ . '/another_folder/');
I18n::setTranslationLanguage('de_DE');

echo __('Add');
// Result: Hinzufügen

echo __("Remove");
// Result: Entfernen

echo __('Remove %s Item\'s ', 3212);
// Result: 3212 Dinge entfernen

echo __('A new string');
// Result: A new string

echo __('A new string with placeholder %s', 'inside');
// Result: A new string with placeholder inside

翻译应用/网站

你可以使用bash脚本来生成翻译文件。请注意,这是一个简单的解决方案。使用=很容易将其破坏。

要翻译网站,你可以使用以下shell命令

php vendor/basteyy/php-i18n/src/bin/I18nBaker source_folder target_file options --no-comments

假设你的文件存储在/var/www/src/templates/下,你应该翻译的文件,你希望将翻译文件存储在/var/www/src/translations/dk_DK.ini,你需要执行以下操作

php vendor/basteyy/php-i18n/src/bin/I18nBaker /var/www/src/templates/ /var/www/src/translations/dk_DK.ini

选项

你可以附加以下选项

--no-comments将输出一个不带任何注释的翻译文件。

php vendor/basteyy/php-i18n/src/bin/I18nBaker /var/www/src/templates/ /var/www/src/translations/dk_DK.ini --no-comments

待办事项

  • 编写测试
  • 向shell命令添加更多选项
  • 创建一个可靠的shell应用(可能使用symfony/console)