I have created 4 columns in database which are title_en, title_ru, content_en, content_ru. however, I dont know what to do next, The datas are going to database successfully but I dont know how to switch the language and what to write in controller and models and views, please can you help to manage it
You can learn from this tutorial.
https://code.tutsplus.com/tutorials/how-to-program-with-yii2-localization-with-i18n--cms-23140
You may swtich language with jquery ajax request.
public function actionChangelang(){
$language = $_GET['lang'];
if($language =='en' || $language == 'uz' || $language == 'ru'){
Yii::$app->language = $language ;
Yii::$app->session->set('lang', $language); //or $_GET['lang']
}
$this->redirect('/'); // redirecting user to somewhere
}
After that, you may write query in controller like this:
...
$model = Yourmodel::find()->all();
...
//TODO
In view :
$lang = 'ru';
if (Yii::$app->language == 'uz')
$lang = 'uz';
if($lang=='uz'){
$title = $model->title_uz ;
$content = $model->content_uz ;
}else{
$title = $model->title_ru;
$content = $model->content_ru;
}
...
//TODO
echo $title;
echo $content;
Related
I have a website with ability to choose language. And I wanted to make that when user enters first time to the website, php gets his system language and writes to cookie (So user by default every time when he enters time will have same language). But when user want to change website language, he will press a button with chosen language (For example Russian), then website language will be set for russian, and when he will enter website again, he will have russian language.
So far I have this code, but it's really confusing and it doesnt work properly.
HTML:
<a href="index.php?language=en">
<a href="index.php?language=ru">
PHP:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if (empty($_COOKIE['language'])){
setcookie('language', $language);
}
if ( !empty($_GET['language']) ) {
$_COOKIE['language'] = $_GET['language'] === 'en' ? 'en' : 'ru';
} else {
switch ($language){
case "ru":
$language = 'ru';
break;
case "en":
$language = 'en';
break;
default:
$language = 'en';
break;
}
}
if ( $_COOKIE['language'] == "en") {
$language = 'en';
} else {
$language = 'ru';
}
$xml = simplexml_load_file("language.xml") or die("Equestria forgot languages");
$s_nav_main = $xml->s_nav_main->$language;
$s_nav_more = $xml->s_nav_more->$language;
$s_nav_bot = $xml->s_nav_bot->$language;
$s_nav_partners = $xml->s_nav_partners->$language;
$s_nav_developer = $xml->s_nav_developer->$language;
$s_aboutus = $xml->s_aboutus->$language;
$s_title = $xml->s_title->$language;
$s_head_title = $xml->s_head_title->$language;
$s_head_info = $xml->s_head_info->$language;
$s_statistics_people = $xml->s_statistics_people->$language;
$s_statistics_online = $xml->s_statistics_online->$language;
$s_statistics_messages = $xml->s_statistics_messages->$language;
$s_why_we_best = $xml->s_why_we_best->$language;
$s_why_we_best_content_title = $xml->s_why_we_best_content_title->$language;
$s_why_we_best_content_info = $xml->s_why_we_best_content_info->$language;
$s_why_we_best_adm_title = $xml->s_why_we_best_adm_title->$language;
$s_why_we_best_adm_info = $xml->s_why_we_best_adm_info->$language;
$s_why_we_best_comfort_title = $xml->s_why_we_best_comfort_title->$language;
$s_why_we_best_comfort_info = $xml->s_why_we_best_comfort_info->$language;
$s_why_we_best_wtf_title = $xml->s_why_we_best_wtf_title->$language;
$s_why_we_best_wtf_info = $xml->s_why_we_best_wtf_info->$language;
$s_trusted_title = $xml->s_trusted_title->$language;
$s_trusted_info = $xml->s_trusted_info->$language;
$s_people_celestia = $xml->s_people_celestia->$language;
$s_people_celestia_comment = $xml->s_people_celestia_comment->$language;
$s_people_luna = $xml->s_people_luna->$language;
$s_people_luna_comment = $xml->s_people_luna_comment->$language;
$s_people_twilight = $xml->s_people_twilight->$language;
$s_people_twilight_comment = $xml->s_people_twilight_comment->$language;
$s_botinfo_info = $xml->s_botinfo_info->$language;
$s_botinfo_more = $xml->s_botinfo_more->$language;
?>
The first place you should look for the users preferred language is the Accept-Language header. Geo-IP lookups are a dangerous and expensive waste of time (at least for determining language). Beyond that, you can set a cookie to override the choices presented by the browser, but there are legal implications around this for websites in Europe.
$avail_lang=array(
'en'=>1,
'fr'=>1,
'de'=>1,
'ru'=>1
);
define("DEFAULT_LANG", 'en');
...
if ($_COOKIE['language'] && isset($avail_lang[$_COOKIE['language']]) {
$use_lang=$_COOKIE['language'];
}
// override with GET if provided
if ($_GET['language'] && isset($avail_lang[$_GET['language']]) {
$use_lang=$_GET['language'];
}
// no language? check browser
if (!$use_lang) {
$request_lang=explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach($request_lang as $i) {
list($lang, $pref)=explode("=", trim($i));
$pref=$pref ? 0.0+$pref : 1.0;
list($lang, $country)=explode("-", $lang);
$pref_lang[$lang]=$pref;
}
rsort($pref_lang);
$use_lang=array_shift(array_intersect_key($pref_lang, $avail_lang));
if (!$use_lang) $use_lang=DEFAULT_LANGUAGE;
}
if (user_accepts_cookies() && $use_lang!=$_COOKIE['language']) {
set_lang_cookie($use_lang);
}
a simple logic can be adopted here -
when a user lands at your website you should track his/her IP address, we can easily get their country using that IP. Then you can easily serve language to them.
Found the way how to do this:
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if ( !empty($_GET['language']) ) {
$_COOKIE['language'] = $_GET['language'] === 'en' ? 'en' : 'ru';
} elseif (empty($_COOKIE['language'])) {
$_COOKIE['language'] = $lang;
}
setcookie('language', $_COOKIE['language']);
if ( $_COOKIE['language'] == "en") {
$language = 'en';
} else {
$language = 'ru';
}
I have a problem recovering a variable in a view.
I followed this tutorial:
Once I have the other view, I can not send a variable so that I can get it back in the view.
Controller.php
public function action_like($token = false, $bID = false)
{
if ($this->bID != $bID) {
return false;
}
if (Core::make('token')->validate('like_page', $token)) {
$page = Page::getCurrentPage();
$u = new User();
$this->markLike($page->getCollectionID(), $page->getCollectionTypeID(), $u->getUserID());
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$b = $this->getBlockObject();
//Normaly we set a variable for get in the view
// $this->set('test', 'test');
$bv = new BlockView($b);
$bv->render('view/view');
} else {
Redirect::page($page)->send();
}
}
exit;
}
view/view.php
<?php echo $test; ?>
<p> Title <p/>
thanks for answers
Sessions provide a way to store information across multiple
requests/pages.
You may use :
//...
$_SESSION["test"] = "test";
//...
I am creating a multilingual site, language switcher loads needed language file but if the file doesn't contain the needed entry, it doesn't appear at all, even default array value is not visible.
I make translation like this:
$lang = "en";
if(isset($_GET['lang'])){
$lang = $_GET['lang'];
}
require_once("languages/lang_".$lang.".php");
Language array:
<?php echo $language["USERNAME"]; ?>
Language file with translation:
$language["USERNAME"] = "User name";
If language file doesn't include $language["USERNAME"] = "User name"; then nothing is showing at all. What I am trying to achieve is: if loaded language file doesn't contain the translation, then array should return the default value, example: USERNAME.
I did check if array key or value is available to show needed information, but seems check is done in loaded language file and if the language file is empty, then there is nothing to show. I just need to show default array value which is located in the main PHP file. If there is no translation for array
<?php echo $language["USERNAME"]; ?>
I want to echo value in brackets: USERNAME.
For that you need to define a default language.
In that case i choose English.
In your language files, try not define a variable, but return the translation array.
If you are using return keyword in language files you can have control about variables, so you can include multiple language files in your script.
Language files
lang_en.php
<?php
return [
'username' => 'username'
];
the same way for the other language files.
index.php
<?php
$lang = "en" // that's default language key
$GLOBALS['defaultLanguage'] = require_once('lang_'.$lang.'.php');
if(isset($_GET['lang'])){
$lang = $_GET['lang'];
}
$GLOBALS['language'] = include('lang_'.$lang.'.php');
if(!is_array($GLOBALS['language']) {
$GLOBALS['language'] = [];
}
echo translate('username');
translate function
/**
* #param string $key
* #return string
*/
function translate($key)
{
$language = $GLOBALS['language'];
$defaultLanguage = $GLOBALS['defaultLanguage'];
if(!isset($language[$key]) || !$language[$key]){
$language[$key] = $defaultLanguage[$key];
}
return $language[$key];
}
Language array:
$language["USERNAME"] = "User name";
File Script
$lang = "en";
if(isset($_GET['lang'])){
$lang = $_GET['lang'];
}
require_once("languages/lang_".$lang.".php");
global $templang = $language;
<?php echo language("USERNAME"); ?>
funtion language($key){
global $templang;
return (isset($templang[$key]))? $templang[$key] : "Default Value";
}
You can try this:
function getTranslatedText($key) {
if(array_key_exists($key, $array_contains_translation_text))
return $array_contains_translation_text[$key];
else
return $array_contains_common_text[$key];
}
getTranslatedText("UserName");
Similar to Andrei Todorut answer, you can simply merge 2 language files, replacing default strings with translated, where non-translated will remain untouched. To achieve this, you can use array_replace function, that will do the trick. This will preserve your $language array, no extra functions needed to check for existence of translated string etc.
Let's assume your language file looks like this:
lang_en.php
<?php
return [
'username' => 'username',
'no-trans' => 'not translated'
];
lang_other.php
<?php
return [
'username' => 'user name'
];
Multilingual array code:
<?php
$lang = "en";
$defaultLanguage = require_once('lang_'.$lang.'.php');
if(isset($_GET['lang'])){
$lang = $_GET['lang'];
}
$translated = include('lang_'.$lang.'.php');
if(is_array($translated)) {
$language = array_replace($defaultLanguage, $translated);
} else {
$language = $defaultLanguage;
}
Output
print_r($language);
// output:
array[
'username' => 'user name',
'no-trans' => 'not translated'
]
echo $language['username'];
// output:
user name
So, after discussion with Newcomer and better understanding some requirements, here is another solution to the problem:
Language files
lang_en.php
<?php
$language["USERNAME"] = "Username";
$language["EMAIL"] = "Email";
$language["PASSWORD"] = "Password";
$language["CREATE_ACCOUNT"] = "Create account";
lang_de.php
<?php
$language["USERNAME"] = "Nutzername";
$language["PASSWORD"] = "Passwort";
Scripts and functions
index.php
<?php
require_once('translate.php');
if(isset($_GET['lang']) && file_exists('lang_'.$_GET['lang'].'.php')) {
include_once('lang_'.$_GET['lang'].'.php');
} else {
include_once('lang_en.php');
}
// print
_e('USERNAME');
// return
__('USERNAME');
translate.php
<?php
function _e($key) {
if(isset($language[$key])) {
echo $language[$key];
} else {
echo $key;
}
}
function __($key) {
if(isset($language[$key])) {
return $language[$key];
} else {
return $key;
}
}
I try to make a 'change languge system' for my script. I already created my class and everything works fine. My problem is next: if I have URL index.php?lang=fr , my website language is changed as long I have ?lang=fr. If I remove ?lang=fr from URL, language is changed too back to english. What is wrong in my conditions ?
P.S: $available_langs is an array with en, fr and ro.
if(isset($_GET['lang']) && $_GET['lang'] != ''){
if(in_array($_GET['lang'], $available_langs)){
$_SESSION['lang'] = $_GET['lang'];
$lang = new Language("languages/");
$lang->setLang($_SESSION['lang']);
} else {
$_SESSION['lang'] = "en";
$lang = new Language("languages/");
$lang->setLang($_SESSION['lang']);
}
} else {
if(isset($_SESSION['lang'])){
$lang = new Language("languages/");
$lang->setLang($_SESSION['lang']);
} else {
$_SESSION['lang'] = "en";
$lang = new Language("languages/");
$lang->setLang($_SESSION['lang']);
}
}
I have two code blocks that are PHP functions that do two different things. They are:
<?php
if (!function_exists('UserPhotoDefaultUrl')) {
function UserPhotoDefaultUrl($User) {
$Email = GetValue('Email', $User);
$HTTPS = GetValue('HTTPS', $_SERVER, '');
$Protocol = (strlen($HTTPS) || GetValue('SERVER_PORT', $_SERVER) == 443) ? 'https://secure.' : 'http://www.';
$Url = $Protocol.'gravatar.com/avatar.php?'
.'gravatar_id='.md5(strtolower($Email))
.'&size='.C('Garden.Thumbnail.Width', 50);
if (C('Plugins.Gravatar.UseVanillicon', FALSE))
$Url .= '&default='.urlencode(Asset('http://vanillicon.com/'.md5($Email).'.png'));
else
$Url .= '&default='.urlencode(Asset(C('Plugins.Gravatar.DefaultAvatar', 'plugins/Gravatar/default.gif'), TRUE));
return $Url;
}
}
and...
<?php
class GravatarPlugin extends Gdn_Plugin {
public function ProfileController_AfterAddSideMenu_Handler($Sender, $Args) {
if (!$Sender->User->Photo) {
$Email = GetValue('Email', $Sender->User);
$Hash = md5($Email);
$Sender->User->Photo = 'http://w'.substr($Hash, 0, 1).'.vanillicon.com/'.$Hash.'_200.png';
}
}
}
The first shows the Gravatar image for User avatar in post content of my script (Vanilla forums), and the second one shows the Vanillicons (Vanillicon is similar to Gravatar) of all the users participating in a discussion in the sidebar (under 'In This Discussion'). I hope you get the idea as to what the two code blocks do now?
Using the how-it's-done code in the first code block, I need to modify the second code block to show Gravatar icons of all users participating in a discussion instead of Vanillicons. Can someone who knows PHP help?
<?php
if (!function_exists('UserPhotoDefaultUrl')) {
function UserPhotoDefaultUrl($User) {
$Email = GetValue('Email', $User);
$HTTPS = GetValue('HTTPS', $_SERVER, '');
$Protocol = (strlen($HTTPS) || GetValue('SERVER_PORT', $_SERVER) == 443) ? 'https://secure.' : 'http://www.';
$Url = $Protocol.'gravatar.com/avatar.php?'
.'gravatar_id='.md5(strtolower($Email))
.'&size='.C('Garden.Thumbnail.Width', 50)
.'&default='.urlencode(Asset(C('Plugins.Gravatar.DefaultAvatar', 'plugins/Gravatar/default.gif'), TRUE));
return $Url;
}
}
you class:
<?php
class GravatarPlugin extends Gdn_Plugin {
public function ProfileController_AfterAddSideMenu_Handler($Sender, $Args) {
if (!$Sender->User->Photo) {
$Sender->User->Photo = UserPhotoDefaultUrl($Sender->User); // not sure about the $Sender->User part because it is not displayed
}
}
}