PHP variable or JSON localization and how to retrieve them - php

I want to implement localization. Once I get the language code, for example, en, what would be the best way to retrieve the text? For example:
en:
welcome-text = "Hello!"
es:
welcome-text = "Hola!"
also, what would be the most efficient and the fastest way? should i store them with php variables and get the text via php variables in an array or switch statement OR should i store them as json and get them via json?

If you are not using some framework (most of them have translation functions and I really suggest you use one) I suggest you arrays as your translation files. It is a simple and fast way:
en.php
<?php return array(
'Welcome' => 'Welcome',
...
);
es.php
<?php return array(
'Welcome' => 'Holla',
...
);
lang.php
<?php
$mapping = require($_SESSION['user-lang-code'].'.php');
funciton _t($text)
{
global $mapping;
return isset($mapping[$text])?$mapping[$text]:$text;
}
Your page:
<?php
require 'lang.php';
echo _t('Welcome');

Related

Multilingual PHP Inline Replacement in HTML ([en]...[/en] etc.)

I am a coding beginner and have my PHP/HTML web project in German. Now I want to make it available in English in the easiest way. I don't want to add other languages in the future, so I want to try it in the easiest (and maybe not the most proper) way.
I have PHP files with HTML content and the selected language available in a var, i.e.:
<?php
$lang = "en";
?>
<h1>Title in German</h1>
So all the German words are inline HTML. My idea was to create something like:
<h1>[de]Title in German[/de][en]Title in English[/en]</h1>
But I have no idea how to replace it on every load in a smart way. So it is more a topic on "live replacement".
Working with constants in an external language file is of course also an option, like all the other options to make a multilingual site I found on Stackoverflow.
But maybe there is a "quick and dirty" possibility option like the one I mentioned?
Thank you for every hint!
You could try and do this will almost only HTML and CSS. You would need to add this at the top of your page:
<?php
$pageLanguage = "en";
function getLanguageStyle($showLanguage)
{
global $pageLanguage;
$display = ($showLanguage == $pageLanguage ? 'inline' : 'none');
return " span.$showLanguage { display: $display }\n";
}
echo "<style>\n".
getLanguageStyle('en').
getLanguageStyle('de').
"</style>\n";
?>
It sets up a style for each language, which you can then use like this:
<h1><span class="de">Title in German</span><span class="en">Title in English</span></h1>
The advantage here is that you don't need to mix HTML and PHP. This is not a normal way of doing this, but it will work. On very complex pages, where these styles are applied after the first render, this might not be pleasant for your visitors.
Usually translations are made that way:
You have key to translation map for each language, then you request some function that takes proper map for that language and returns translation:
function translate(string $lang, string $key) {
/*
* This usually sits in some file in dir like `/src/i18n/en.json`
* And you do then `$translations = json_decode(require "/src/i18n/{$lang}.json")`
*/
$translations = [
'en' => [
'page.title' => 'Page Title',
...
],
'de' => [
'page.title' => 'Page Title In German',
...
],
];
return $translations[$lang][$key] ?? $key;
}
<h1><?= translate($lang, 'page.title'); ?></h1>

Include problems with PHP

I need a little help! I'm making multilangual site with php and I got an issue. I want to include array into another array.
There is one php file
<?php
$lang = array(
'en' => array(
include ('translations/nav-translation/en.php');
),
'lv' => array(
include ('translations/nav-translation/lv.php');
),
);
?>
And php file that I want to include
<?php
"home" => "Home",
"blog" => "Blog",
"about" => "About me",
?>
If you don't want to use yaml it's better to return arrays from your lang files
en.php:
<?php
return ["home" => "Home",....]
?>
index.php:
<?php
$lang = array(
'en' => include("translations/nav-translation/en.php"),
'lv' => ....
Can't you just set up your include files like this:
translations/nav-translation/en.php
<?php
$lang['en'] = array(
"home" => "Home",
"blog" => "Blog",
"about" => "About me"
);
?>
And then:
<?php
$lang = array();
include ('translations/nav-translation/en.php');
include ('translations/nav-translation/lv.php');
?>
Seems a lot less complicated than any other suggestion.
To create a multilingual PHP site, I'd suggest using a function that checks the language the user has specified and then loading the text from a database or use JSON.
Using JSON
Create a file with a .txt extension, create your translations in JSON format and read it via PHP, to read the file in PHP use:
$json = json_decode(file_get_contents($file),TRUE);
You can then use the JSON data to set variables within PHP to display the correct language.
Using a database
Have your database setup like this:
---------------------------
Lang | Short | Text
---------------------------
In your database, set up as many languages as you want, have the lang column the two-letter abbreviation of the language name, the short should be the name of the text, so if it was the home page title, name the short home-title and then the text should be the text that you want to be displayed in your desired language.
Using a database will allow you to add/edit languages and translations via the database.
$path = 'translations/nav-translation';
$user_lang = 'nl'; // determine what the user actually wants
$fallback_lang = 'en';
if (file_exists("{$path}/{$user_lang}.php")) {
include ("{$path}/{$user_lang}.php");
} else {
include ("{$path}/{$fallback_lang}.php"); // nominate a default
}
In the language files (e.g. translations/nav-translation/en.php), offer a fully formed associative array:
$lang = [
"home" => "Home",
"blog" => "Blog",
"about" => "About me"
];
Then, back in your original file after the conditional include call, you can reference $lang['home'] or [cringe] use extract()* to generate variables like $home.
*note, I have never, ever used extract() in any of my projects, there are risks in using it -- I'm just saying you could.

PHP Custom CMS - How to handle settings

I'm currently trying to find a way to handle settings on my custom CMS (just a playground to learn PHP). I have database table that stores all settings. My temporary solution is a function that returns one dimensional array with query results.
// Get settings from db.
function getPanelOptions( $pdo ) {
$options = [];
$getOptions = $pdo->query( 'SELECT option_name, option_value FROM bp_options' );
while( $result = $getOptions->fetch() ) {
$options[ $result['option_name'] ] = $result['option_value'];
}
return $options;
}
$bpOptions = getPanelOptions( $pdo ); // Get settings to arr.
// Example use
if( $bpOptions['post_max_lenght'] === 400 ) ...
I've read a lot that global variables are not best way to do this, so I call function in file that is included on every page. I don't have problem with using hard coded variable, because I won't change it (even so I can replace all occurrences in sublime). My biggest problem is that I can't find a way to use settings to create a 'wrapper' functions like in WordPress, for example 'getHtmlLang()'. In JS it would be easy, but in PHP I need to pass setting to this function, at it gets to lengthy.
// Now i use
<html lang="<?php echo $bpOptions['panel_lang']; ?>">
// I'd like some wrapper function.
<html <?php getHtmlLang() ?>>
I'm not familiar with OOP in PHP so maybe this is way to achieve this, or should I simply use global because it's justified?

Allowing users to make template- Scan code for functions

I am currently creating a web app and I would like to allow my users to create a template. I would only allow them to use HTML and some functions to get some values, so I have some functions like
getDescription(); but since its PHP I also have other function (e.g. phpinfo();) which I don't want them to use.
Is it possible to set a filter (like in_array) to check if functions other than declared are used?
Or is there an Template engine or something else which does that.
I am very new to templating and I couldn't find anything.
If they are only creating HTML templates, you could allow them to put for example;
<div>
[PHP]getDescriptions()[PHP]
</div>
<div>
[PHP]phpinfo()[/PHP]
</div>
Then in your parsing file when they save or whatever, you could have
$allowedFunctions = array('getDescriptions');
$input = '';//html from the template
foreach($allowedFunctions as $key => $value){
$myVal = $value();
$input = str_replace('[PHP]'.$value.'()[/PHP]',$myVal,$input);
}
This would replace [PHP]getDescriptions()[/PHP] with whatever is returned from getDescriptions()...
and phpinfo() wouldnt change.
you can check if a function exists with function_exists. If you want them to use the functions you defined for that purpose only you could prefix those function with something like 'tpl_*". like this:
function tpl_getDescription() {/*code here*/}
and then when you user tries to implement a function like getDescription you add "tpl_" to it and check if that function exists with function_exists().
if(function_exists('tpl_' . $userFuncName))
{
call_user_func('tpl_' . $userFuncName)
}
that way even if the user tries to evoke a native php function tpl_ will be prefixed and if will return false.
Yes, you could easily make a script that enumerates all user functions in an external file. Lets say you have this "template", template.php :
<?
function getDescription() {
}
function userFunc() {
}
function anotherFunction() {
}
?>
then you could get a list of all functions in template.php this way :
<?
include('template.php');
$functions = get_defined_functions();
echo '<pre>';
print_r($functions['user']);
echo '</pre>';
?>
would output :
Array
(
[0] => getdescription
[1] => userfunc
[2] => anotherfunction
)
I would call this script through AJAX, like getfunctions.php?file=template.php which returned a JSON with all user functions inside template.php.

Mustache php gettext()

I am experimenting with kostache, "mustache for kohana framework".
Is there any way I can use simple PHP functions in mustache template files.
I know logic and therefore methods are against logic-less design principle, but I'm talking about very simple functionality.
For example:
gettext('some text') or __('some text')
get the base url; in kohana -> Url::site('controller/action')
Bobthecow is working on an experimental feature that will allow you to call a function as a callback.
Check out the higher-order-sections branch of the repository and the ticket to go with it.
You could use "ICanHaz" http://icanhazjs.com/
and then you can declare your mustache templates as
<script id="welcome" type="text/html">
<p>Welcome, {{<?php echo __('some text') ?>}}! </p>
</script>
Well, you can do this now with Bobthecow's implementation of Mustache Engine. We need anonymous functions here, which are passed to the Template Object along with other data.
Have a look at the following example:
<?php
$mustache = new Mustache_Engine;
# setting data for our template
$template_data = [
'fullname' => 'HULK',
'bold_it' => function($text){
return "<b>{$text}</b>";
}
];
# preparing and outputting
echo $mustache->render("{{#bold_it}}{{fullname}}{{/bold_it}} !", $template_data);
In the above example, 'bold_it' points to our function which is pasalong withwith other data to our template. The value of 'fullname' is being passed as a parameter to this function.
Please note that passing parameters is not mandatory in Mustache. You can even call the php function wothout any parameters, as follows:
<?php
# setting data for our template
$template_data = [
'my_name' => function(){
return 'Joe';
}
];
# preparing and outputting
echo $mustache->render("{{my_name}} is a great guy!", $template_data); # outputs: Joe is a great guy!
Credits: http://dwellupper.io/post/24/calling-php-functions-for-data-in-mustache-php

Categories