Hướng dẫn php multi language

by Vincy. Last modified on July 13th, 2022.

Nội dung chính

  • What is inside?
  • Why a website needs multi-language support?
  • Ways to add multi-language support to a website
  • About this example
  • PHP example files created to enable multi-language-support
  • Database script
  • How to make a web page HTML for multi-language support
  • How to switch the language of the content in PHP
  • Multi-language PHP example demo
  • PHP example output – multilingual page supporting two-languages
  • How do I add PHP multilingual support to my website?
  • How can I create a multi language website?
  • How can I translate a PHP language?
  • How do I make a multilingual website in HTML?

A website with the Multi-language support gains the readership world-wide. 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. By supporting these languages, you can bring a new audience to your website.

There are multilingual websites that support more than 50 languages. Choosing the supporting language for your website is on the basis of various factors. Mostly, it depends on the content and the audience to whom you are writing.

A website with multi-language support contains the following controls or features.

  • A menu or input to switch the content language.
  • Loads content in the reader’s language by default.
  • To allow default language configuration if the reader’s language is not supported.
  • Switching static and dynamic content as per the language selected.
  • Converting page URLs based on the selected language.

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.

Hướng dẫn php multi language

In this tutorial, we are going to create a web page with multi-language support using PHP. It shows both static and dynamic content. The dynamic content is from the database.

What is inside?

  1. Why a website needs multi-language support?
  2. Ways to add multi-language support to a website
  3. About this example
  4. PHP example files created to enable multi-language-support
  5. Database script
  6. How to make a web page HTML for multi-language support
  7. How to switch the content language in PHP
  8. Muti-language PHP example demo
  9. PHP example output – multilingual page supporting two-languages

Why a website needs multi-language support?

In the introductory part, we saw the two major need of enabling multi-language support on a website. The below list shows some more reasons why we need this support for our website.

  • It helps to position yourself that you are creating content for the world audience.
  • It will build your brand regardless of the country, people and language.
  • It will make the readers shortlist you among your competitors.
  • It will be proof of your dedication and support to your readers.

Ways to add multi-language support to a website

There are various ways to enable Multi-language support for an application.

  1. By having duplicate pages with the same content in the required languages.
  2. By managing language configuration (localization) with files containing texts in different languages.

Instead of having duplicate pages, I prefer the second method. Because the first method will lead inconsistency among the duplicate pages.

By implementing localization with files, it will load content on a page template. This template is common for all languages. It will prevent the disadvantage of the first method.

About this example

In this example, the multilingual page shows both static and dynamic data. It changes the static data on a language basis by using the corresponding language file. For switching the language of the dynamic data, the code adds a suitable prefix to the array indexes.

I will provide multilingual support with two languages English and German. So, the database column_name will be en_column_name and de_column_name.

PHP example files created to enable multi-language-support

This is the example files created for enabling two-language support on a web page using PHP.

The below image shows the language files and SQL files along with the file hierarchy.

Database script

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;

How to make a web page HTML for multi-language support

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. In the page header, it shows the language menu with ‘English‘, ‘Deutsche‘ languages.

Each language menu targets the page link with the lang parameter. By clicking the menu, it 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 the people suffered 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">
    <h2>Enable Multi-Language Support for a Webpage in PHP</h2>
</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
}
?>

In this HTML, I have displayed the language links in a horizontal menu bar. 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 language code instead of the full name. Or, we can make it as a dropdown menu.

How to switch the language of the content in PHP

This example page includes the following to display as texts.

  • Page title
  • Language menu
  • Database results
  • No-results-found message

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 the 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 both the database and the non-databased content.

Loading non-database text from the language files

On clicking language links, I pass the selected language code in the Querystring. 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 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, 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 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 to 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 is a common class available in the free download zip at the end of this article.

Multi-language PHP example demo

I have deployed a demo page for this example. View the demo to see how the PHP multi-language code works. I have provided the demonstration with the dual-language switch control.

View Demo

PHP example output – multilingual page supporting two-languages

These screenshots show the page content in the selected English and German languages. It highlights the selected language in Orange.

Conclusion

We have seen how to add multi-language support for a webpage using PHP. This example includes both a database and the non-database content. We have seen how to switch the language of these content on 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 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.

download

↑ Back to Top

How do I add PHP multilingual support to my website?

Ways to add multi-language support to a website There are various ways to enable Multi-language support for an application. By having duplicate pages with the same content in the required languages. By managing language configuration (localization) with files containing texts in different languages.

How can I create a multi language website?

How to Build a Multi Language Site Using a Website Builder: 9 Steps.

Choose the best website builder for you..

Sign up to the right plan for you..

Register a unique domain name..

Pick a template you love..

Customize your design..

Add and format (and translate) your site's content..

Make it multilingual!.

How can I translate a PHP language?

php class Translator { private $language = 'en'; private $lang = array(); public function __construct($language){ $this->language = $language; } private function findString($str) { if (array_key_exists($str, $this->lang[$this->language])) { echo $this->lang[$this->language][$str]; return; } echo $str; } private ...

How do I make a multilingual website in HTML?

Approach.

keep track of a list of phrases and translations for each of the three languages..

provide the correct list of phrases to polyglot based on user input..

use an html data attribute to store the phrase name in the html..

hard-code the default translation in the html..