clean and simple PHP multi-language app scheme

7 Mar 2025 | clean and simple PHP multi-language app scheme |

Just a very short post on how to quickly and easily display multi-lingual web page content in basic PHP web pages or apps for a variety of languages. Of course you can run always webpage through a translation app, but this more often than not have unintended results as JavaScript heavy apps generally get corrupted in the language translation along with session variable issues and other user scoped parameters.

There are many other PHP multi-lingual web page approaches , you can read about them here: php – Best practice multi language website – Stack Overflow , most as you’ll recognize require complex structural setups or tooling and generally are over engineered if all you need is your app or web page to change a few important labels into another language.

Suggested Simpler Language approach

A simpler an equally effective language approach is to simply write the language bits in HTML with a simple but human readable coding technique, like {LANG_EN: "Hello", LANG_ES: "ola"}. all inside the same HTML and simply have PHP parse out the appropriate language snippet.

<?php

function replaceHTMLContent($html, $language) {
    // Define a regular expression pattern to match the placeholders
    $pattern = '/{LANG_EN: \"(.*?)\", LANG_ES: \"(.*?)\"}/';

    // Use preg_replace_callback to replace each placeholder with its corresponding value based on the language
    $resultingHtml = preg_replace_callback($pattern, function($matches) use ($language) {
        if ($language === "EN") {
            return $matches[1];
        } else {
            return $matches[2];
        }
    }, $html);

    return $resultingHtml;
}

// Example usage:
$htmlContent = '<p>{LANG_EN: "Hello", LANG_ES: "ola"}</p> <p>{LANG_EN: "Welcome", LANG_ES: "Bienvenido"}</p>';
$language = "EN"; // You can change this to "ES" or any other language

$resultingHtml = replaceHTMLContent($htmlContent, $language);

echo $resultingHtml;

?>
  1. Pattern Definition : A regular expression pattern is defined to match the placeholders in the format {LANG_EN: "Hello", LANG_ES: "ola"}.
  2. preg_replace_callback : The preg_replace_callback function is used to replace each matched placeholder with its corresponding value based on the chosen language ($language). Inside the callback function:
    • If $language is "EN", it returns the value from the first capturing group (i.e., matches[1]).
    • Otherwise, it returns the value from the second capturing group (i.e., matches[2]).

This approach ensures that the values inside the placeholders are directly extracted and used for replacement. This allows you to keep all the language text in easy to edit HTML while separating the PHP coding logic via language selection paramters..

Here’s an exmaple of an HTML page that makes a javascript fetch request to update the language content.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Language Test Page</title>
</head>
<body>
    <h1>Choose a Language</h1>
    <select id="languageSelect" onchange="updateContent()">
        <option value="">Select a language</option>
        <option value="EN">English (EN)</option>
        <option value="ES">Spanish (ES)</option>
        <option value="FR">French (FR)</option>
    </select>

    <div id="content">
        <!-- Placeholder content -->
        <p>{LANG_EN: "Hello", LANG_ES: "ola", LANG_FR: "bonjour"}</p>
        <p>{LANG_EN: "Welcome", LANG_ES: "Bienvenido", LANG_FR: "Bienvenue"}</p>
    </div>

    <script>
        function updateContent() {
            var languageSelect = document.getElementById('languageSelect');
            var selectedLanguage = languageSelect.value;
            var contentDiv = document.getElementById('content');

            // Fetch the HTML content and replace placeholders
            fetch('content.php?lang=' + selectedLanguage)
                .then(response => response.text())
                .then(htmlContent => {
                    contentDiv.innerHTML = htmlContent;
                });
        }
    </script>
</body>
</html>

Here’s the corresponding content.php that the Ajax request above calls.

<?php
header('Content-Type: text/html; charset=utf-8');

// Get the selected language from the query parameter
$language = isset($_GET['lang']) ? $_GET['lang'] : 'EN';

// Define an associative array with placeholders and their translations based on language
$replacements = [
    "{LANG_EN: \"Hello\", LANG_ES: \"ola\", LANG_FR: \"bonjour\"}" => ($language === "EN") ? "Hello" : ($language === "ES") ? "ola" : "bonjour",
    "{LANG_EN: \"Welcome\", LANG_ES: \"Bienvenido\", LANG_FR: \"Bienvenue\"}" => ($language === "EN") ? "Welcome" : ($language === "ES") ? "Bienvenido" : "Bienvenue"
];

// Loop through the replacements and replace them in the HTML content
foreach ($replacements as $search => $replace) {
    echo str_replace($search, $replace, file_get_contents('content.html'));
}
?>

This works best for apps

This approach works best when you’re just replacing small bits of text like labels among a small selection of languages (less than 4 works best) in your web app. It’s not very convenient if you’re replacing paragraph length amounts of text or have a half a dozen language, but realistically this will never be the caase. If you look at any international websites, they usually limit the language choices to 3-6 (native language, English, Spanish, …. 1 or 2 more popular regional languages…”

Leave a Reply