PHP Internationalization (i18n): A Practical Developer's Guide

more

Yee

Aug 03, 2024

cover-img

Take Your PHP Website Global: A More Efficient Internationalization Solution

If you're like me and maintain "vanilla" PHP projects that don't rely on big frameworks (like Laravel or Symfony), then multi-language support (i18n) has probably been a persistent—if minor—pain point.

The traditional solution, gettext, while powerful, is pretty cumbersome to set up. Especially for small projects, it feels like using a sledgehammer to crack a nut. What we really need is a method that can be implemented quickly, without adding too much complexity.

After a lot of trial and error across several projects, we've come up with a lightweight internationalization solution based on PHP array files and online translation tools. This approach is not only easy to deploy, but it also has extremely low maintenance costs. Today, I'm sharing this whole solution with you—no strings attached.

Hands-on Guide: How I Nailed PHP Multi-language Support with O.Translator

Our core idea is super straightforward: Each language gets its own PHP file, which contains a return statement that returns an associative array. This method is simple, intuitive, and has minimal performance overhead.

Step 1: Plan Your Directory Structure

A clear directory structure is half the battle. To keep things organized, we'll put all our language files in the same folder and name them using language codes, like this:

project_root/
├── index.php         // Your main logic file
├── i18n/             // Folder for all language files
│   ├── lang.cn.php   // Chinese language pack
│   ├── lang.en.php   // English language pack
│   └── lang.fr.php   // French language pack

Step 2: Build Your "Language Arsenal"

Next, let's create the base language file. We'll use Chinese as an example and make a lang.cn.php file. This file is just a simple PHP array, where the keys are unique identifiers and the values are the actual text strings.

lang.cn.php example: Keys stay the same, values change with the language

Step 3: Meet the Translation Wizard—O.Translator

Manually translating dozens or even hundreds of entries? That's exactly the kind of repetitive work programmers hate most. That's where our secret weapon, O.Translator, comes in.

It's a professional online translation platform that fully supports PHP files, so it can read your array directly and translate it into over 70 languages.

The process is ridiculously simple:

  1. Head over to the O.Translator homepage and upload your base language file (for example, lang.cn.php).
  2. Pick your target languages, like English and French.
  3. Hit translate, wait a moment, and your translated lang.en.php and lang.fr.php files will be ready for download.

What really impressed me is that O.Translator lets you preview part of the translation for free. If you like what you see, you can then decide whether to pay for the full translation. In their own words: "Never pay for a product you're not happy with."

Step 4: Bring Your Code to Life

Everything’s ready; all that’s left is the final touch. Now, let’s tweak your main index.php file so it can dynamically load the right language pack based on the user’s choice.

<?php

// 1. Determine the current language (using a GET parameter for demonstration)
$supported_langs = ['en', 'cn', 'fr'];
$default_lang = 'en';
$lang = isset($_GET['lang']) && in_array($_GET['lang'], $supported_langs) ? $_GET['lang'] : $default_lang;

// 2. Load the corresponding language file
// Use a global variable like $_ or a specific variable like $TEXTS to store the strings
$_ = require_once __DIR__ . "/i18n/lang.{$lang}.php";

?>

In your HTML template, you can easily call the text strings like this:

<!DOCTYPE html>
<html lang="<?php echo htmlspecialchars($lang); ?>">
<head>
    <meta charset="UTF-8">
    <title><?php echo htmlspecialchars($_['heading_home']); ?></title>
</head>
<body>
    <header>
      <h1><?php echo htmlspecialchars($_['heading_home']); ?></h1>
      <nav>
        <ul>
          <li><?php echo htmlspecialchars($_['heading_about']); ?></li>
          <li><?php echo htmlspecialchars($_['button_read_more']); ?></li>
        </ul>
      </nav>
    </header>
</body>
</html>

And there you have it—a simple multi-language website is born!

Considerations and Advanced Thinking

While this solution is lightweight, there are a few points worth considering before deploying to production:

  • How do you detect the user's language? The example uses a GET parameter like ?lang=en. In a real application, you could also use $_SESSION, $_COOKIE, or parse the browser's Accept-Language request header for automatic detection.
  • Performance Considerations: For small to medium-sized websites, the performance overhead of require_once for a PHP file on each request is negligible. If your site has high traffic, consider using bytecode caching technologies like APC or OPcache for further optimization.
  • Scalability: As the number of languages or text strings grows, managing files manually can become complicated. At that point, you might need to explore more professional i18n solutions, such as PHP's gettext extension or the localization components provided by frameworks.
  • Translation Consistency: To keep brand names and terminology consistent across all language versions, we highly recommend using O.Translator's Glossary feature.
  • High-level Strategy: This article focuses on the technical implementation. If you want to learn more about the overall strategy for website internationalization, check out our other in-depth article.

Theme

scenario

scenario

Published Articles11

Recommended reading