A translator using GetText
Find a file
2025-09-08 13:13:43 +02:00
I18N Updating tests files. 2025-09-06 16:47:45 +02:00
src refs #8: Fix 2025-09-08 13:13:43 +02:00
tests refs #5: Using vendor/autoload.php in the main tests bootstrap script. 2025-09-06 18:37:17 +02:00
.gitignore refs #5: Using vendor/autoload.php in the main tests bootstrap script. 2025-09-06 18:37:17 +02:00
codeception.yml Fix in codeception config file. 2025-09-06 18:53:06 +02:00
composer.json Require PHP gettext extension and codeception for development. 2025-09-06 18:52:41 +02:00
README.md Update README.md 2025-09-08 12:55:49 +02:00

Translator

Description

A translator library using PHP gettext extension.

Install

Install with composer:

composer require iwalkalone/translator

Or a specific version:

composer require iwalkalone/translator ^1.7

How to use it

Example code to autodetect language using headers sent by client:

$available_languages = [
  'en_GB',
  'en_US',
  'ca_ES',
  'es_ES',
];
$default_language = 'ca_ES';
$path_to_translations = './locale';
$translator = new \iwalkalone\Translator($available_languages, $default_language, $path_to_translations);
$str = 'Hello!';
$translated = $translator->translate($str);

It also accepts placeholders. In next example, %username% is replaced for Mark after getting the translation.

$str = 'Hello %username%!';
$translated = $translator->translate($str, [
  'username' => 'Mark',
]);

You can disable language autodetection, specifying one:

$translator = new \iwalkalone\Translator($available_languages, $default_language, $path_to_translations, 'en_GB');

Be sure to generate all locales you want to use editing /etc/locale-gen and running locale-gen as root.

Compile translations:

It is as simple as:

$translator->compile();

By default it searches in ./I18N directory, but you can customize it:

$translator->compile("/path/to/translations");

If you want to compile it with JSON format:

$translator->compileJson("/path/to/translations", "/path/to/JSON/output");

Running tests:

install PHP libraries with composer

composer install

Run tests with codecept:

vendor/bin/codecept run