Skip to content

Instantly share code, notes, and snippets.

@Jengas
Created June 2, 2018 12:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jengas/14fdf627e4b76681dfa31df1b3d6729e to your computer and use it in GitHub Desktop.
Save Jengas/14fdf627e4b76681dfa31df1b3d6729e to your computer and use it in GitHub Desktop.
PHP + XML + COOKIES language system
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Languages used to generate menus and for template translations
$languages = [
['id' => 'en', 'title' => 'English', 'icon' => 'US'],
['id' => 'es', 'title' => 'ESPAÑOL'],
['id' => 'ru', 'title' => 'РУССКИЙ'],
['id' => 'cn', 'title' => '中国'],
['id' => 'de', 'title' => 'Deutsch (Soon)'],
];
// Collect allowed languages
$allow_langs = array_map(function ($lang) {
return $lang['id'];
}, $languages);
<?php require("language.php"); ?>
<!DOCTYPE html>
<html lang="ru" class="home-page">
<head>
<title>Wassup!</title>
</head>
<body>
<h1><?= trans('exmaple1')?></h1>
<h1><?= trans('exmaple2?></h1>
</body>
</html>
<?php
include_once(__DIR__. '/config.php');
/**
* Translate by key
*
* @param $key
* @return string
*/
function trans($key)
{
global $xml, $language, $allow_langs;
$lang = $language;
$value = null;
// Language fallback
if (!in_array($lang, $allow_langs, true)) {
$lang = 'en';
}
// Get value
$value = trim($xml->{$key}->{$lang});
// Fallback to english
if ($value === '1' || empty($value) || is_null($value )) {
$lang = 'en';
$value = trim($value = $xml->{$key}->{$lang});
}
return trim($value);
}
$browser_lang = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
$language = (isset($_COOKIE['language']) ? $_COOKIE['language'] : $browser_lang);
if (isset($_GET['language'])) {
$language = $_GET['language'];
}
if (!in_array($language, $allow_langs, true)) {
$language = 'en'; //fallback for invalid lang
}
setcookie('language', $language);
$xml = simplexml_load_file( __DIR__. "/language.xml") or die("Pony destroyed language!");
?>
<?xml version="1.0" encoding="UTF-8"?>
<lang>
<exmaple1>
<en>Example 1</en>
<ru>Пример 1</ru>
<es>Example 1</es>
</exmaple1>
<exmaple2>
<en>Example 2</en>
<ru>Пример 2</ru>
<es>Example 2</es>
</exmaple2>
</lang>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment