Multi language PHP scripting

in


Assume we have to build a multi language website; on this website are several texts which have to be translated: "home", "read more" etc. How should we solve the "translation problem" from a scripting side of view?

When building a website some code with the likes of:

echo '<a href="./read_text.php?' . $id . '"> read more </a>';

can usually be found.

If you would like to extend your website beyond the English language we have to make some adjustments there. Several options can be considered as a solution:

  1. We can use a multidimensional array in order to store the translations:
    $static_text = array();
    $static_text['eng']['read_more'] = 'read more';
    $static_text['spa']['read_more'] = 'seguir leyendo';
    echo '<a href="./read_text.php?' . $id . '">' . $static_text[$current_lang]['read_more'] . '</a>';
  2. We can use multiple files to store a translation in a variable and preferably using a variable prefix (_st):
    require_once( '/language/' . $current_lang . '.php' );
    echo '<a href="./read_text.php?' . $id . '">' . $_st_read_more . '</a>';
  3. We can use multiple files to store a translation in a constant:
    require_once( '/language/' . $current_lang . '.php' );
    echo '<a href="./read_text.php?' . $id . '">' . READ_MORE . '</a>';

Both 2 and 3 can easily be extended since we only have to add a single file when a new translation is required; however note this technique could also be used for 1.

From a programmers viewpoint I prefer number 3 since the interpreter gives a warning when a constant is misspelled or not in use and it increases the readability of the code.

Back to top