A website with Multi-language support gains readership worldwide. It shows its content in different languages based on the user selection.
There are many non-English speaking countries around the world. The readers from the region may want to read content in their languages. You can bring a new audience to your website by supporting these languages.
There are multilingual websites that support more than 50 languages. Choosing the supporting language for your website is based on various factors. Mostly, it depends on the content and the audience you are writing to.
A website with multi-language support contains the following controls or features.
In this way, the multi-lingual features vary as per the nature of the application. We have seen how to create a multi-language WordPress site using Google Language Translator.
In this tutorial, we will create a web page with multi-language support using PHP. It shows both static and dynamic content. The dynamic content is from the database.
In the introductory part, we saw the two primary needs to enable multi-language website support. The below list shows some more reasons why we need this support for our website.
There are various ways to enable Multi-language support for an application.
Instead of having duplicate pages, I prefer the second method because the first method will lead to inconsistency among the duplicate pages.
It will load content on a page template by implementing localization with files. This template is standard for all languages. It will prevent the disadvantage of the first method.
In this example, the multilingual page shows both static and dynamic data. It uses the corresponding language file to change the static data on a language basis. The code adds a suitable prefix to the array indexes for switching the dynamic data’s language.
I will provide multilingual support in two languages English and German. So, the database column_name will be en_column_name and de_column_name.
These are the example files created for enabling two-language support on a web page using PHP.
The image below shows the language and SQL files and the file hierarchy.
This is the SQL script that contains the required table structure and data. Create a development database and import this script into it.
Configure the DataSource with appropriate credentials. Then, run this example in your PHP environment.
sql/tbl_newsletter.sql
--
-- Database: `blog_samples`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_newsletter`
--
CREATE TABLE `tbl_newsletter` (
`id` int(11) NOT NULL,
`en_title` varchar(255) NOT NULL,
`en_description` text NOT NULL,
`de_title` varchar(255) NOT NULL,
`de_description` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tbl_newsletter`
--
INSERT INTO `tbl_newsletter` (`id`, `en_title`, `en_description`, `de_title`, `de_description`) VALUES
(1, 'Example Content', 'It was popularised in the 1960s with the release of Letraset sheets containing passages, and more recently with desktop publishing software like Aldus PageMaker including versions', 'Beispiel Inhalt', 'Bekannt wurde es 1960, mit dem erscheinen von \"Letraset\", welches Passagen von enhielt, so wie Desktop Software wie ebenfalls mit.'),
(2, 'Usage Example', 'The standard chunk of used since the 1500s is reproduced below for those interested. Also reproduced in their exact original form.', 'Anwendungsbeispiel', 'Der Standardteil von, genutzt seit 1500, ist reproduziert für die, die es interessiert abgeleitet von der Englischen Version aus.');
--
-- Indexes for table `tbl_newsletter`
--
ALTER TABLE `tbl_newsletter`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for table `tbl_newsletter`
--
ALTER TABLE `tbl_newsletter`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
This is a one-page example for supporting multi-language using PHP. This page will show the page title, language menu, and tabular data from the database.
There is static text content shown in this example web page. Those are the page title and the no-record-found text. These texts are from the PHP language files.
There are two language files created for this example. The page header shows the language menu in ‘English’ and ‘Deutsche‘ languages.
Each language menu targets the page link with the lang parameter. Clicking the menu loads the content based on the selected language.
HTML language specification:
I set the HTML element lang attribute with the selected language code. It will help people suffering from visual impairments to read your content.
With this specification, the screen reader tool can read the content audible to the users.
index.php
<?php
namespace Phppot;
require_once ("./Model/NewsLetter.php");
use Phppot\DataSource;
$newsLetter = new NewsLetter();
$result = $newsLetter->getAllRecords();
?>
<html lang="<?php echo $lang; ?>">
<head>
<title>How to Enable Multi-language Support to Website using PHP</title>
<link href='./assets/css/phppot-style.css' rel='stylesheet'
type='text/css' />
<link href='./assets/css/multi-lingual-page.css' rel='stylesheet'
type='text/css' />
</head>
<body>
<div class="phppot-container">
<?php require_once "./view/home.php"; ?>
</div>
</body>
</html>
view/home.php
<div class="page-heading">
<h1>Enable Multi-Language Support for a Webpage in PHP</h1>
</div>
<div class="language-header">
<div class="demo-page-title"><?php echo $language["LIST_TITLE"]; ?></div>
<div class="language-link">
<a class="language-link-item" href="index.php?lang=en"
<?php if($lang == 'en'){?> style="color: #ff9900;"
<?php } ?>>English</a> | <a class="language-link-item"
href="index.php?lang=de" <?php if($lang == 'de'){?>
style="color: #ff9900;" <?php } ?>>Deutsche</a>
</div>
</div>
<?php
if (! empty($result)) {
foreach ($result as $k => $v) {
?>
<div class="demo-row-data">
<div>
<strong><?php echo $result[$k][$lang.'_title']; ?></strong>
</div>
<p class="demo-row-description"><?php echo $result[$k][$lang.'_description']; ?>
</p>
</div>
<?php
}
} else {
?>
<div class="no-result"><?php echo $language["NOTIFY_NO_RESULT"]; ?></div>
<?php
}
?>
I have displayed the language links in a horizontal menu bar in this HTML. And I displayed the full name of the languages for these links.
In the case of supporting more languages, there may occur a space constraint. In such cases, we can make the language menu scrollable horizontally.
Otherwise, we can display the language code instead of the full name. Or, we can make it a dropdown menu.
This example page includes the following to display as texts.
From the above, the page title and the no-results-found texts are static. I am managing the language-based content for these texts with files.
I have created language configuration (localization) files for English and German. They contain an array of text to display for this example.
view/Language/lang.en.php
<?php
$language['LIST_TITLE'] = 'Popular Tutorial';
$language["NOTIFY_NO_RESULT"] = "No Results Found";
?>
view/Language/lang.de.php
<?php
$language["LIST_TITLE"] = "Populair Zelfstudie";
$language["NOTIFY_NO_RESULT"] = "Geen Resultaten Gevonden";
?>
The database table contains separate columns for English and German. Look at the below screenshot.
The below section describes the code to load content based on the selected language. It covers how to change the language for the database and the non-databased content.
Loading non-database text from the language files
When clicking language links, I pass the selected language code in the query string. The selected language code is set with a PHP variable $lang. I interpolate this variable while including the language configuration file. The code is
index.php (code to load language file based on selected language)
<?php
// include language configuration file based on selected language
$lang = "en";
if(isset($_GET['lang'])){
$lang = $_GET['lang'];
}
require_once("./view/Language/lang.".$lang.".php");
?>
...
<div class="demo-page-title"><?php echo $language["LIST_TITLE"]; ?></div>
...
<div class="no-result"><?php echo $language["NOTIFY_NO_RESULT"]; ?></div>
How to localize content from the database
In the PHP code, we connect the DataSource and execute the query to fetch the results.
We have seen that the database column name has the language prefix. There are separate title and description columns with en_ and ‘de_ prefix’. They have the data in English and German language.
On iterating the database results, I embed the $lang prefix with this title and description array index. Then, it shows the appropriate language-based results.
view/home.php (code to display database results in the selected language)
<?php
if(!empty($result)){
foreach($result as $k=>$v){
?>
<div class="demo-row-data">
<div><strong><?php echo $result[$k][$lang.'_title']; ?></strong></div>
<p class="demo-row-description"><?php echo $result[$k][$lang.'_description']; ?>
</p>
</div>
<?php
}
}
?>
This is a PHP model class NewsLetter.php. It prepares database queries and invokes DataSource to process them. It fetches and returns data from the database in a dual language.
Model/NewsLetter.php
<?php
namespace Phppot;
use \Phppot\DataSource;
class NewsLetter
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getAllRecords()
{
$query = 'select * from tbl_newsletter';
$result = $this->ds->select($query);
return $result;
}
}
This is a generic DataSource library. I created this class to handle database operations.
This class includes functions to perform the database CRUD operations. It also includes functions to calculate results count and bind query parameters.
In this example, I need only the functions to read data from the database. So, the below code shows the code snippet from the DataSource. You can find the complete code in the source code downloadable.
DataSource.php
This standard class is available in the free download zip at the end of this article.
I have deployed a demo page for this example. View the demo to see how the PHP multi-language code works. I have provided a demonstration of the dual-language switch control.
These screenshots show the page content in the selected English and German languages. It highlights the selected language in Orange.
We have seen how to add multi-language support for a webpage using PHP. This example includes both database and non-database content. We have seen how to switch the language of this content by selecting a language.
PHP makes it simple to achieve this. We have implemented multi-language support with a minimal number of files and code.
If you want to test with more languages, create corresponding language files. The language file you created must contain the appropriate name with a prefix. This code will give you a base platform to build an advanced multilingual feature on top of it.
I hope this code simplifies your effort to turn your application multilingual.