callismart / i18n
Gettext-compatible translations for PHP apps without WordPress or the gettext extension: PO, MO and compiled PHP catalogs, plural rules, locale fallback and negotiation, plus tools to extract strings, merge and compile catalogs.
Requires
- php: >=8.1
- ext-ctype: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.64
- phpunit/phpunit: ^10.5 || ^11 || ^12
Suggests
- ext-intl: Shows each language's name in its own language for every locale, not only the built-in list.
- ext-mbstring: Capitalizes language names from ext-intl correctly.
- ext-tokenizer: Required by StringExtractor to read PHP sources (enabled in most PHP builds).
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-06 11:54:29 UTC
README
Translations for PHP applications, compatible with gettext files and without the gettext extension or WordPress:
- a translator that reads
.po,.moand compiled.l10n.phpcatalogs, with text domains, contexts, plural rules for every language, regional fallback (pt_BR→pt) and override directories; - a locale resolver that picks a request's language from the URL, the
user's preference, a cookie, the site setting or
Accept-Language; - tools that extract strings from PHP and JavaScript into a
.pottemplate, start and update translations (likemsginitandmsgmerge) and compile them (likemsgfmt, plus a fast.l10n.phpformat).
composer require callismart/i18n
It requires PHP 8.1+ with ext-ctype (on by default) and nothing else; the
string extractor also needs ext-tokenizer (likewise on by default). With
ext-intl, every locale can name itself in its own language (Français,
日本語); without it, a built-in list covers the common ones.
Translating
use Callismart\I18n\I18n; use Callismart\I18n\Translator; $translator = new Translator( 'fr_FR', null, 'my-app' ); // locale, loaders, default domain $translator->add_directory( 'my-app', __DIR__ . '/languages' ); I18n::set_translator( $translator ); $translator->translate( 'Save changes' ); // "Enregistrer les modifications" $translator->translate( 'Post', null, 'verb' ); // context (msgctxt) $translator->translate_plural( '%d file', '%d files', $count ); // the language's plural rule $translator->translate( 'Invoice sent.', 'acme-invoices' ); // another text domain
Passing null as the domain means the translator's default domain
(messages unless you set one). Untranslated text comes back unchanged.
Files are looked up as {directory}/{domain}-{locale}.{ext}. For each
directory and each locale in the fallback chain, the first of .l10n.php,
.mo and .po wins. A directory added later takes precedence, and catalogs
from several directories are merged, so a site can override a few strings and
still fall back to the bundled ones.
Other translator methods:
| Method | What it does |
|---|---|
set_locale( 'de_DE' ), get_locale() |
Change or read the active Locale |
with_locale( 'de_DE', fn () => ... ) |
Run code in another language (emails to a user), then restore |
available_locales( $domain ) |
Locales with a compiled catalog, plus en_US |
add_catalog( new Catalog( [...] ) ) |
Add translations from code; they win over files |
on_missing( fn ( $text, $domain, $locale ) => ... ) |
Hear about strings without a translation |
on_error( fn ( Throwable $e, string $path ) => ... ) |
Hear about catalog files that cannot be read (they are skipped) |
Your own helper functions
Most applications wrap the translator in short global functions. They are yours to name; the extractor learns them (see below).
function acme__( string $text, ?string $domain = null ) : string { return \Callismart\I18n\I18n::translator()->translate( $text, $domain ); } function acme_n( string $single, string $plural, int $count, ?string $domain = null ) : string { return \Callismart\I18n\I18n::translator()->translate_plural( $single, $plural, $count, $domain ); }
Until I18n::set_translator() runs (early errors, unit tests), I18n::translator()
is a source-language translator, so the helpers always work.
Choosing the language
use Callismart\I18n\LocaleResolver; $resolver = new LocaleResolver( $translator->available_locales(), 'acme_lang' ); // cookie name $locale = $resolver->resolve_http( $_GET, $_COOKIE, $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null, $user_language, // the signed-in user's preference, or null $site_language, // the administrator's choice, or null ); $translator->set_locale( $locale );
The first available match wins, in this order: ?lang= in the URL, the user's
preference, the cookie, the site setting, Accept-Language (where fr
matches fr_FR), then en_US. Only installed languages are accepted, so a
stale preference never breaks a page. resolve() takes the same values
without an HTTP request.
Locale normalizes identifiers (pt-br, zh-Hans-CN) and tells you
code(), to_bcp47() for <html lang>, direction() (rtl for Arabic,
Hebrew, Persian, Urdu, ...) and native_name(). I18n::language_options()
lists the installed languages for a picker, as code => native name.
JavaScript
CatalogCompiler writes the strings used in .js files to a separate
{domain}-js-{locale}.l10n.php catalog, so pages only send what scripts need.
I18n::script_data() returns everything a browser-side helper needs: locale,
lang, dir, the plural rule and the default domain's script strings, plus
other domains registered with I18n::add_text_domain() under domains.
$translator->add_directory( 'my-app-js', __DIR__ . '/languages' ); echo '<script>const i18nData = ' . json_encode( I18n::script_data() ) . ';</script>';
Messages are keyed by msgid, or context . "\x04" . msgid, with the plural
forms as a list. The plural rule is a gettext Plural-Forms header. A small
helper can then provide __(), _x(), _n() and _nx().
Tools
The tools run in your own build script or console command.
use Callismart\I18n\Locale; use Callismart\I18n\Po\PoDocument; use Callismart\I18n\Tools\CatalogCompiler; use Callismart\I18n\Tools\PoMerger; use Callismart\I18n\Tools\StringExtractor; // 1. Extract a template from the sources. $extractor = new StringExtractor( 'my-app', base_dir: __DIR__, php_functions: StringExtractor::PHP_FUNCTIONS + StringExtractor::prefixed_functions( 'acme' ), skip_paths: [ 'src/helpers.php' ], ); $pot = $extractor->extract( [ __DIR__ . '/src', __DIR__ . '/templates', __DIR__ . '/assets/js' ] ); $pot->save( __DIR__ . '/languages/my-app.pot' ); foreach ( $extractor->warnings() as $warning ) { echo $warning, "\n"; // e.g. a helper called with a variable: it can never be translated } // 2. Start or update a translation. $merger = new PoMerger(); $po = is_file( $path = __DIR__ . '/languages/my-app-fr_FR.po' ) ? $merger->merge( $pot, PoDocument::from_file( $path ) ) : $merger->init( $pot, Locale::parse( 'fr_FR' ), 'My App 1.0' ); $po->save( $path ); print_r( PoMerger::stats( $po ) ); // total, translated, fuzzy, percent // 3. Compile it: writes .l10n.php, .mo and the -js catalog next to the .po. ( new CatalogCompiler( 'my-app i18n compile' ) )->compile( $path );
The extractor reads:
- PHP calls to the functions in its map: by default
__,_e,_x,_ex,_n,_nx,_n_noop,_nx_noop,esc_html__/_e/_xandesc_attr__/_e/_x.prefixed_functions( 'acme' )addsacme__,acme_e,acme_x,acme_n,acme_nx,acme_esc_html__and the rest. - JavaScript calls to
__,_x,_nand_nx, bare or as a property (i18n.__()). Passjs_functionsfor other names. translators:comments on the line before a call, for the translators.
Calls with no domain, or 'default', belong to default_domain (the extracted
domain unless you say otherwise), so you can extract an extension's domain
from the same sources. By default it skips vendor, node_modules, .git,
dist and tests directories (skip_dirs), plus .min.js and .l10n.php files.
Tests
composer install vendor/bin/phpunit composer cs:check
The .mo compatibility test runs when GNU msgfmt is installed.
License
MIT. See LICENSE.