W3docs

Best practice multi language website

One best practice for implementing a multi-language website in PHP is to use a language detection library such as Text-Language-Detect.

One best practice for implementing a multi-language website in PHP is to detect the user's preferred language using the $_SERVER['HTTP_ACCEPT_LANGUAGE'] header. This returns a language tag that you can parse to extract the ISO 639-1 code. (Note: Production implementations often use dedicated detection libraries to handle complex Accept-Language headers, but this example demonstrates the core PHP logic.)

You can then use the ISO code to lookup the appropriate translation in a language translation file or database. (Note: The example below uses a hardcoded array for demonstration; in practice, this should be loaded from a database or i18n package.)

To display the translated content on your website, you can use a combination of PHP and HTML. For example, you can use PHP to output the translated content inside an HTML element like a div or p tag.

Here is an example of how you can use PHP to display translated content on a multi-language website:

Example of using PHP to display translated content on a multi-language website

<?php
// 1. Determine the active language (query param > browser header > default)
// Note: In production, use a proper parser/library to handle quality values and subtags.
$activeLang = $_GET['lang'] ?? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$activeLang = in_array($activeLang, ['en', 'fr', 'es']) ? $activeLang : 'en';

// 2. Translation lookup (placeholder: use a database, JSON file, or i18n package in production)
$translations = [
    'en' => ['welcome' => 'Welcome to our website!'],
    'fr' => ['welcome' => 'Bienvenue sur notre site !'],
    'es' => ['welcome' => '¡Bienvenido a nuestro sitio web!'],
];

// Fallback to English if the key or language is missing
$message = $translations[$activeLang]['welcome'] ?? $translations['en']['welcome'];
?>

<div>
    <p><?= $message ?></p>
    <a href="?lang=en">English</a> |
    <a href="?lang=fr">Français</a> |
    <a href="?lang=es">Español</a>
</div>

It's also a good idea to use a language switcher on your website to allow users to easily switch between languages. This can be implemented as a dropdown menu or a list of links that update the URL query parameter or route, as shown above. For better user experience, consider persisting the selected language using cookies or sessions so it remains consistent across requests.