How to translate your website using PHP
Learn how to translate your PHP website using methods like gettext, YAML, JSON, and arrays. Choose the best approach add PHP multilingual support to your site
Introduction
While PHP multilingual support is not required for most projects, it's always a good idea to prepare your code for it. You never know when the user base of your website or application may change. Most of the time, you can include this support without making significant code changes or spending many hours on it. If you're using a PHP framework, it might be even easier to set up.
In this blog, I will skip frameworks and go back to the basics. I prefer to avoid framework overhead when building my own projects.
Before we start, it's important to decide which method we'll use to translate our website or application. There are at least four ways to do this: the old-school method with PO/MO files, a modern approach using YAML, or the simplest and lightest method using a PHP array or YAML. As you can see, there are plenty of options. Personally, I recommend using YAML or a simple PHP array, as these are the fastest and most lightweight options.
When setting up PHP multilingual support in your code, make sure the default language is English. Why English, you ask? It's simple using English ensures that others can easily read your code, and if you go international, other developers will understand it. Using languages like Dutch or Japanese in your project can make it harder for others to follow.
Using gettext for Translation
Let's start with adding PHP multilingual support to your website using PO/MO files, also known as gettext. This is a built-in PHP method available since version 4. While this approach has largely been replaced by more modern methods like YAML and JSON, we'll focus on gettext for now. The main advantage of using gettext is that it’s built into PHP and is still supported by some legacy applications. However, the downside is that editing PO/MO files can be cumbersome, as it requires external applications.
Installation
Depending on your server environment, PHP gettext might already be installed. If not, you may need to install the php-gettext
package or contact your web hosting provider.
# For Linux (Debian/Ubuntu)
sudo apt-get install php-gettext
# For macOS (if using Homebrew)
brew install gettext
Create your language files using the Poedit application and place them in the folder structure shown below:
locales/
|── en_US/
| └── LC_MESSAGES/
| └── messages.po
| └── messages.mo
└── es_ES/
└── LC_MESSAGES/
└── messages.po
└── messages.mo
Code example
To use the translations within your code you can use the gettext() method or _t() in your code as shown in the PHP code example below.
// Set locale and domain
$locale = 'es_ES';
putenv("LANG=$locale");
setlocale(LC_ALL, $locale);
// Specify the location of the translation files
bindtextdomain("messages", "./locales");
textdomain("messages");
// Use translated strings
echo _("Hello, World!"); // Output: ¡Hola, Mundo!
In addition to the gettext()
method, PHP provides support for pluralization in translations, which isn't easily achievable with other methods like YAML, JSON, or PHP arrays. This feature can be particularly useful when dealing with languages that have complex plural forms. However, for most projects, the difference in using pluralization support may be minimal, especially if your application only requires simple, singular translations. Nonetheless, if your website needs precise language handling for different plural cases, gettext()
could be a valuable option to consider.
YAML-Based Translations
Another great option for adding PHP multilingual support to your PHP website is using YAML. One of the main advantages of YAML is that it’s more human-readable and easier for non-developers to understand, which makes it an excellent choice for projects where translations are managed by non-technical team members. While JSON is also relatively easy to work with, it can be more difficult to manage compared to YAML, and plain PHP arrays are even more complex for non-developers to grasp. Therefore, the choice between YAML, JSON, and PHP arrays ultimately depends on the level of usability required for your team and project.
Installation
Both JSON and PHP arrays work out of the box with PHP, but if you choose to use YAML for your translations, you'll need to install a vendor module. Specifically, you'll need to use Composer to install the symfony/yaml
module, which provides the necessary functionality for parsing and handling YAML files.
composer require symfony/yaml
To integrate YAML into your codebase, you first need to create a .yml
file. The structure of a typical YAML file is simple and easy to read, as shown below.
app:
settings:
theme: dark
timezone: "America/New_York"
When you want to use this in your PHP application or website you will have to import the YAML file. This can be done with a single line of code.
$config = Yaml::parseFile('nested.yaml');
echo $config['app']['settings']['theme'];
To use this method for adding PHP multilingual support. You could create a function or a static class.
require 'vendor/autoload.php';
use Symfony\Component\Yaml\Yaml;
class Translator
{
private static $translations = [];
private static $locale = 'en';
// Load translations from a YAML file
public static function load($locale, $filePath)
{
self::$translations[$locale] = Yaml::parseFile($filePath);
}
// Set the current language
public static function setLocale($locale)
{
self::$locale = $locale;
}
// Get a translation
public static function trans($key, $placeholders = [])
{
$translation = self::$translations[self::$locale][$key] ?? $key;
// Replace placeholders like {name}
foreach ($placeholders as $placeholder => $value) {
$translation = str_replace("{" . $placeholder . "}", $value, $translation);
}
return $translation;
}
}
use the code below to execute the code from the static class from above:
// Load translation files
Translator::load('es', 'translations/es.yaml');
// Set to Spanish
Translator::setLocale('es');
// Output: Bienvenido
echo Translator::trans('welcome');
JSON-Based Translations
If you want to keep the translation process simple and efficient, JSON is an excellent choice. It’s one of the easiest methods to implement translations into your website, requiring only three components: the JSON file containing the translations, the method to load the translations, and the code that fetches the translations to display in your view.
One of the main benefits of using JSON is that it doesn’t require any additional modules or plugins for your PHP environment. This makes it a lightweight solution that can be used seamlessly in any PHP-based project without any compatibility issues. Since JSON is widely supported and easy to parse, it’s an ideal choice for smaller projects or when you want a straightforward implementation.
Example JSON File
Here’s what a simple JSON file might look like. For simplicity, I’ve opted for a flat, key-value structure. While it’s possible to group translations into nested levels, I recommend avoiding this approach. Nesting can lead to duplication issues when working with multiple modules, making the translation process more cumbersome and harder to manage.
{
"clock": "klok",
"banana": "Banaan"
}
Example PHP code
The PHP method shown below can be used to fetch the translations and output the given text based on the given key. One side note as this is only a preview the code is not optimized.
$translations = json_encode(
file_get_contents('translations.json'),
true
);
function translate(array $translations, string $string) {
return $translations[$string] ?? $string;
}
echo translate('clock');
PHP Array Translations
Another way to translate your website is by using a plain PHP array. This method works similarly to the JSON approach, where translations are stored as key-value pairs. However, there are some drawbacks. First, you need to have a basic understanding of PHP to manage the translation structure effectively. Additionally, if there's a mistake in the PHP array structure, it can cause your entire application or website to break, which can be a hassle to debug.
For these reasons, I personally wouldn’t recommend using this method unless you have a small, simple project and are comfortable with PHP. That said, it's still an option worth mentioning.
Below, I’ve included an example of how to implement translations using a PHP array:
$translations = [
"clock": "klok",
"banana": "Banaan"
];
function translate(array $translations, string $string) {
return $translations[$string] ?? $string;
}
echo translate('clock');
Conclusion
I hope you learned something new from this blog. There are several other ways to add PHP multilingual support to your PHP website or application, and some of these concepts can even be applied to other programming languages. It's important to choose the method that best fits the framework you're using. For example, if you're developing with WordPress, the gettext method is recommended since it's the default for that platform. Personally, when I build my own PHP projects, I avoid frameworks to maintain full control and minimize overhead. In these cases, I prefer using the JSON method for translations. Whatever approach you choose, be consistent throughout your project.