PHP code example of wufr / php-language-localizer

1. Go to this page and download the library: Download wufr/php-language-localizer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wufr / php-language-localizer example snippets


use wUFr\Translator;

$translator = new Translator(
    dir: __DIR__ . '/locales/',  // Directory containing the language directories
    lang: 'en_US'                // Language directory to read
);

echo $translator->locale('common/general', 'welcome');
// Welcome to our application

$translator
    ->setDirectory(__DIR__ . '/locales/')
    ->setLanguage('cs_CZ')
    ->setFallbackLanguages('en_US');


// locales/en_US/common/general.php

return [
    'welcome' => 'Welcome to our application',
    'greeting' => 'Hello, {name}!',
    'logout' => 'Log out',
];

// 'greeting' => 'Hello, {name}!'
echo $translator->locale('common/general', 'greeting', ['name' => 'John']);
// Hello, John!

// 'welcome' => '<strong>Welcome</strong>, {name}!'
echo $translator->locale('users/profile', 'welcome', ['name' => '<script>alert(1)</script>']);
// <strong>Welcome</strong>, &lt;script&gt;alert(1)&lt;/script&gt;!

use wUFr\Localizer\Raw;

// One value, from PHP code
$translator->locale('legal/terms', 'accept', [
    'link' => new Raw('<a href="/terms">' . htmlspecialchars($title) . '</a>'),
]);

// Named values, e.g. from a template where objects are awkward to build
$translator->locale('legal/terms', 'accept', ['link' => $html, '_raw' => ['link']]);

// All values of one call
$translator->locale('mail/plain', 'body', ['name' => $name, '_raw' => true]);

// Every call, for output that never reaches HTML (plain-text e-mails, CLI)
$translator->setEscaping(false);

// 'total' => 'Total: {amount, number}'   → cs_CZ: "Total: 1 234,5",  en_US: "Total: 1,234.5"
// 'price' => 'Price: {amount, number, 2}' → exactly two fraction digits
// 'share' => 'Share: {ratio, number, percent}'
// 'rounded' => '{amount, number, integer}'
// 'created' => 'Created {when, date}'      → short | medium (default) | long | full
// 'at' => 'At {when, time}'                → short (default) | medium | long | full
// 'on' => 'On {when, datetime}'

// locales/pl_PL/shop/cart.php
return [
    'items' => [
        0 => 'Your cart is empty',   // integer keys match that exact number
        'one' => '{count} produkt',  // 1
        'few' => '{count} produkty', // 2–4, 22–24, 32–34, …
        'many' => '{count} produktów', // 5–21, 25–31, …
        'other' => '{count} produktu', // fractions: 1.5
    ],
];

echo $translator->locale('shop/cart', 'items', ['_counter' => 22]); // 22 produkty
echo $translator->locale('shop/cart', 'items', ['_counter' => 25]); // 25 produktów

$translator->getPluralRules()->define('xx', fn(int|float|string $n): string => $n == 1 ? 'one' : 'other');

// 'itemCount' => [
//     0 => 'You have no items',
//     1 => 'You have one item',
//     2 => 'You have {count} items',
// ]

echo $translator->locale('shop/cart', 'itemCount', ['_counter' => 12]);
// You have 12 items

use wUFr\Gender;

// 'welcome' => [
//     'male' => 'Welcome Mr. {name}',
//     'female' => 'Welcome Mrs. {name}',
//     'neutral' => 'Welcome {name}',
//     'entity' => 'Product: {name}',
// ]

echo $translator->locale('users/welcome', 'welcome', ['_gender' => Gender::Female, 'name' => 'Jane']);
// Welcome Mrs. Jane

// 'items' => [
//     'male' => ['one' => 'He has {count} item', 'other' => 'He has {count} items'],
//     'female' => ['one' => 'She has {count} item', 'other' => 'She has {count} items'],
// ]

echo $translator->locale('users/inventory', 'items', ['_gender' => 'female', '_counter' => 3]);
// She has 3 items

$translator->setLanguage('de_AT')->setFallbackLanguages('de_DE', 'en_US');

$translator = new Translator([
    __DIR__ . '/app/locales/',        // project overrides
    __DIR__ . '/vendor/acme/ui/locales/', // base translations
], 'en_US');

$translator->getDirectory();   // the first directory
$translator->getDirectories(); // all of them

use wUFr\Localizer\MissingTranslation;

// Log and return the identifier
$translator->setMissingHandler(function (MissingTranslation $missing) use ($logger): string {
    $logger->warning($missing->message());
    return htmlspecialchars($missing->identifier());
});

// Fail loudly in development and tests
$translator->setMissingHandler(fn(MissingTranslation $missing) => throw new \RuntimeException($missing->message()));

if ($translator->has('admin/menu', 'reports_desc')) {
    echo $translator->locale('admin/menu', 'reports_desc');
}

public function __construct(string|array $dir = 'locales/', string $lang = 'en_US')

public function locale(string $file, string $key, array $params = []): string
public function has(string $file, string $key): bool

public function setDirectory(string|array $dir): self
public function setLanguage(string $lang): self
public function setFallbackLanguages(string ...$languages): self
public function setEscaping(bool $escape): self
public function setMissingHandler(?callable $handler): self
public function setPluralRules(PluralRules $pluralRules): self

public function getDirectory(): string
public function getDirectories(): array
public function getLanguage(): string
public function getFallbackLanguages(): array
public function isEscaping(): bool
public function getPluralRules(): PluralRules

enum Gender: string
{
    case Male = 'male';
    case Female = 'female';
    case Neutral = 'neutral';
    case Entity = 'entity';

    public function getDescription(): string
}
bash
composer 

locales/
    en_US/
        common/
            general.php
            errors.php
        admin/
            dashboard.php
    cs_CZ/
        common/
            general.php
        ...