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;
}
}
Related
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;
I using prestashop 1.6 and I have some variable in my index.tpl like as $aslist that I Don't know where this variable is defined or assigned!
I need to find this variable and do some change over that.
anybody know how can I find a solution that show where smarty variables assigned ?
I need to a address file like as:
$aslist assigned in .\www\controllers\front\CmsController.php - (line 58 )
You can add this function to config/config.inc.php
function log_smarty_assign($var_name)
{
$smarty_var_filter = 'aslist';
if ($var_name == $smarty_var_filter)
{
$log = '';
$trace = debug_backtrace(false);
if (isset($trace[1]))
{
$log .= 'Variable '.$var_name.' assigned in ';
$log .= $trace[1]['file'].' #'.$trace[1]['line'];
echo "<pre>$log</pre>";
}
}
}
Edit: $trace[1] should be used instead of $trace[2]
And then search for the smarty assign method and modify it to something like this:
I found it in /tools/smarty/sysplugins/smarty_internal_data.php
public function assign($tpl_var, $value = null, $nocache = false)
{
if (is_array($tpl_var)) {
foreach ($tpl_var as $_key => $_val) {
if ($_key != '') {
$this->tpl_vars[$_key] = new Smarty_variable($_val, $nocache);
//log the assignment
log_smarty_assign($_key);
}
}
} else {
if ($tpl_var != '') {
$this->tpl_vars[$tpl_var] = new Smarty_variable($value, $nocache);
//log the assignment
log_smarty_assign($tpl_var);
}
}
return $this;
}
Output example:
Variable product assigned in ...\classes\controller\Controller.php #180
Whenever I leave my input field empty, $error['commment'] should be set and echoed, but it won't echo, but if I just say echo "some text";, it echo's it.
The comments function is in my functions.php file and $error[] = array() is given in my text.php file above my comments() function, so I don't understand why it's not working, please help guys.
The last bit of PHP code is in a while loop that has to display all the results of my SQL query.
Code above my HTML in text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
comments();
?>
Code in my functions.php:
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
$filledIn = true;
if (empty($text)) {
$error['comment'] = "No text filled in";
$filledIn = false;
}
}
}
This is the code in my text.php:
<?php
if(isset($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Because $error is not in the scope of the comments() function. So $error['comment'] never gets set.
Ideally you would want to do something like this:
text.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error['comment'] = comments();
functions.php
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
if (empty($text)) {
return "No text filled in";
}
}
return null;
}
text.php
<?php
if(!empty($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Rather than setting the array key "comments" directly I would use a return value from the comments() function to set it. This allows you to avoid having to use global variables.
Edit: I removed the $filledIn variable from comments() because it wasn't being used in the provided code.
#pu4cu
imo, since you dont come across as very advanced, so that you dont have to make many code changes to what you have now which might get you the minimal edits, and easiest for you to understand;
if in your comment function, you just return a response from this function, like a good little function does, then your response will be available when you call the function, when you set that function to a variable.
//functions.php (note this sets error to true to be failsafe, but this depends on how your using it. set the $response to an empty array in the first line instgad, i.e. array(); if you don't want it failsafe.
<?php
function comments()
{
$response = array(
'error' => TRUE,
'filledIn' => FALSE
);
if (isset($_POST['submit']))
{
$text = $_POST['text'];
$response['filledIn'] = TRUE;
if (empty($text))
{
$response['error']['comment'] = "No text filled in";
}
else{
$response['error'] = NULL;
}
}
return $response;
}
//index.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$response = comments();
//text.php
<?php
if($response['error']['comment'])) echo "<p class='error'>".$response['error']['comment']."</p>";
I find your code overly complicated, 3 files, 2 includes, and 1 function, when all you really needed is this:
$error = array();
$error['comment'] = empty($_POST['text']) ? "No text filled in" : $_POST['text'];
echo "<p class='error'>".$error['comment']."</p>";
Your scopes are all mixed up. Your comments() function checks for $_POST, which should be checked before the function is called, and then tries to set a variable within its scope, but you try to access the same variable from outside.
The correct way would be:
text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
if (isset($_POST['submit']) {
comments($_POST);
}
?>
functions.php
function comments($data){
if (isset($data['text'])) {
$text = $data['text'];
if (empty($text)) {
return array('comment' => 'No text filled in');
}
return true;
}
return null;
}
Then you can use the values returned by your function on to act on the result.
I want to write a simple if statement using HTTP_ACCEPT_LANGUAGE function that redirects based on result of what the users browser language is. I am still a beginner so am obviously keeping it as simple as possible. This is what I have so far but the "if" statement needs work. Can anyone help me with a fix?
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ($lang=german) {
header("Location: http://www.example.com/german/index.html");
} else if ($lang=spanish) {
header("Location: http://www.example.com/spanish/index.html");
}
else if ($lang=french) {
header("Location: http://www.example.com/french/index.html");
}
else if ($lang=chinese) {
header("Location: http://www.example.com/chinese /index.html");
} else {
echo "<html>english content</html>";
}
?>
I don't know what your language literals are, so I'd say make them ISO language codes.
Use a switch statement, this is more readable and smaller:
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
switch($lang) {
case "de-DE":
case "es-ES":
case "cn-CN":
case "fr-FR":
header("Location: http://www.example.com/$lang/index.html");
break;
default:
header("Location: http://www.example.com/en-US/index.html");
break;
}
Further, you are assigning, not comparing. You compare with ==:
if ($lang == "de-DE")
Assuming you always redirect to /language/, you could do it this way:
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ( in_array( $lang,array("german","spanish","french","chinese") ) ) {
header("Location: http://www.example.com/$lang/index.html");
} else {
echo "<html>english content</html>";
}
?>
Also, the comparisons in your if need to be done with ==, it's assignment otherwise!
Try this:
<?php
$path = array(
'en-US' => 'english',
// etc
);
$accepts = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if (in_array($accepts[0], $path)) { // if path exists for language then redirect to path, else redirect to default path (english)
header('Location: http://www.example.com/' . $path[$accepts[0]] . '/index.html');
} else {
header('Location: http://www.example.com/english/index.html');
}
?>
HTTP_ACCEPT_LANGUAGE returns not "english", but two signs symbol like "en", or region and language symbol like "en_us". You shouldn't use if statement it's hard to read. You should use array (in future you can simple write it to config files, or move to databases).
The proper code should look that:
$default_lang = 'en';
$lang_redirectors = array('de' => 'http://www.example.com/german/index.html',
'en' => 'http://www.example.com/english/index.html');
function redirect($url){
header("Location: " . $url);
}
$hal = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$langs = explode($hal, ',');
foreach($langs as $lang){
$lang_prefix = substr($lang, 0, 2);
if(in_array($lang_prefix, $lang_redirectors)){
redirect($lang_redirectors[$lang_prefix]);
break;
}
redirect($lang_redirectors[$default_lang]);
}
<?php
$browserlang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$lang = $browserlang[0] . $browserlang[1] . $browserlang[2] . $browserlang[3] . $browserlang[4];
if (($lang=="sk_SK") OR ($lang=="sk-SK")) {
header("Location: https://www.example.sk/sk");
}
else if (($lang=="en_EN") OR ($lang=="en-EN") OR ($lang=="en_GB") OR ($lang=="en_US") OR ($lang=="en-GB") OR ($lang=="en-US")) {
header("Location: https://www.example.sk/en");
}
else {
header("Location: https://www.example.sk/en");
}
?>
I have 2 questions
1.) how to write update_defile($array_value){...} function?
define_file.php
<?php
define("FIST_NAME", "something1");
define("LAST_NAME", "something2");
define("ADDRESS", "something3");
?>
"something" is not a constant value that can be change every method Call(update_defile($array_value)
value set
$array_value = ("FIST_NAMe" => "duleep", "LAST_NAME" => "dissnayaka", "AGE" => "28" );
after call method(update_defile($array_value){.....}) "define_file.php"
file want to be look like bellow
<?php
define("FIST_NAME", "duleep");
define("LAST_NAME", "dissnayaka");
define("ADDRESS", "something3");
define("AGE", "28");
?>
2).
My datbase is Oracle. I already saved configuration value in the data base but frequently use these configuration value for my application. So i get value form database and save in the define_file.php as increase performance(down rate database call) but I'm not sure i can increase performance keep configuration value in the PHP file please explain. what is the best way increase performance my application and other alternative solutions welcome.
Why cant u use session to store such values , then u can access and modify from anywhere
in the script.
<?php
session_start();
$_SESSION["FIST_NAME"]= "something1";
$_SESSION["LAST_NAME"]= "something2";
$_SESSION["ADDRESS"]= "something3";
?>
public function update($form_config_arr)
{
if( (is_readable($config_file_path)) && is_writable($config_file_path))
{
if(!$config_old_file_content = file_get_contents($config_file_path))
{
throw new Exception('Unable to open file!');
}
$i = 0;
$config_old_arr = array();
$config_new_arr = array();
foreach ($form_config_arr as $constant => $value){
$config_old_line = $this->getLine($constant);
$config_old_arr[$i] = $config_old_line;
if(($value == 'true') || ($value == 'false')){
$config_new_arr[$i] = "define ( '$constant', $value );\n";
}else{
$config_new_arr[$i] = "define ( '$constant', '$value' );\n";
}
$i++;
}
$config_new_file_content = str_replace($config_old_arr, $config_new_arr, $config_old_file_content);
$new_content_file_write = file_put_contents($config_file_path, $config_new_file_content);
foreach ($config_new_arr as $constant => $value)
{
echo $value.'<br/>';
}
return true;
}else{
throw new Exception('Access denied for '.$config_file_path);
return false;
}
}
/**
*
* #param string $constant
* #return string
*/
private function getLine($constant)
{
$match_line = '';
$config_file = fopen($config_file_path, "r");
if($config_file)
{
//Output a line of the file until the end is reached
$i = 0;
while(!feof($config_file))
{
$i++;
$config_old_line = fgets($config_file);
$pos = strpos($config_old_line, $constant);
if( $pos !== false )
{
$match_line= $config_old_line;
}
}
fclose($config_file);
return $match_line;
}else{
throw new Exception('Unable to open file!');
}
}
What you are trying to do is edit a file.
Simply create another php script: updater.php
It should poll the database, fetch the values and update the values in define_file.php
Look for php file handling functions here: http://www.w3schools.com/php/php_file.asp