Last active
January 26, 2018 00:32
-
-
Save luckyshot/dbc68b956ba1aa81cfb27199e68b35ab to your computer and use it in GitHub Desktop.
Multi-language system in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// config.php | |
$config['language'] = []; | |
$config['language']['default'] = 'en'; // no file for this language exists, will be just echoed as is | |
$config['language']['list'] = [ | |
'en' => '🇺🇸 English', | |
'es' => '🇪🇸 Español', | |
]; | |
// router.php | |
$app->load_language( @$app->user['language'], substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) ); | |
// es.php | |
$d = []; | |
$d["Dashboard"] = "Panel de Control"; | |
$d["Hello %1!"] = "¡Hola %1!"; | |
return $d; | |
// app.php | |
function load_language( $lang1, $lang2 = null ){ | |
if ( array_key_exists($lang1, $this->config['language']['list']) ){ | |
$language = $lang1; | |
}else if ( array_key_exists($lang2, $this->config['language']['list']) ){ | |
$language = $lang2; | |
}else{ | |
$language = $this->config['language']['default']; | |
} | |
if ( file_exists(__DIR__.'/langs/'.$language.'.php') ){ | |
$this->dictionary = include __DIR__.'/langs/'.$language.'.php'; | |
} | |
} | |
function _( $string, $vars = [] ){ | |
if ( array_key_exists($string, $this->dictionary) ){ | |
$return = $this->dictionary[ $string ]; | |
}else{ | |
$return = $string; | |
} | |
$i = 1; | |
foreach ($vars as $var) { | |
$return = str_replace( '%' . $i, $vars[ $i-1 ], $return ); | |
$i++; | |
} | |
return $return; | |
} | |
// example.php | |
$app->_('Hello %1!', ['Xavi']); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment