A
A
Anastasia2020-05-28 19:13:46
PHP
Anastasia, 2020-05-28 19:13:46

How to translate a page in PHP?

I have a business card site. The client wanted to add two more languages ​​for it. I don't want to make a separate folder and duplicate the code.
Some data needs to be mapped from the DB.
Plus, you may have to add new languages ​​in the future, so it's important to think about that as well.

What is the best and fastest way to implement this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikolay Panaitov, 2020-05-28
@Picknice

Добавляешь в таблицы поля, что-то типа 
было text
стало text, text_en, text_sp, text_pl  и т.д.
$lang = $_GET['lang']; // Допустим lang хранится в гет параметре (можно и в куки хранить выбранный язык)
$lang = in_array( $lang, [ 'ru', 'en', 'sp', 'pl' ] ) ? "_$lang" : ''; // Получается так "_ru" (вместо ru язык выбранный) или пустая строка.
При генерации страницы где выводишь $row['text'] заменяешь на $row["text$lang"].
Что касается статичных данных, то проще хранить шаблоны для каждого языка и подключать при генерации страницы.

B
bestauction, 2020-05-29
@bestauction

What you are looking for is called i18n (short for internationalization). There are many ways to implement. If you use a framework, then this mechanism is most likely already there (google for *framework name* i18n). If samopis, then here is a simple example.
All static text from the code can be put into a separate json file (or just a php file that returns an array, and include it).
The file must contain a multidimensional array of the form

return [
            'ru' => [
                'text1' => 'текст 1',
                'text2' => 'текст 2'
            ],
            'en' => [
                'text1' => 'text 1',
                'text2' => 'text 2'
            ],
            'es' => [
                'text1' => 'texto 1',
                'text2' => 'texto 2'
            ]
        ];

If different languages ​​are also in the database, then you need to either duplicate the tables, or create additional fields with language prefixes. It already depends on the structure of the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question