Dynamically switch content in website based on user language selection - php

I am designing a small, simple website that will need two languages. I want to keep things simple. I would like to use placeholders/variables in the code that will have user-visible text. Then, allow the user to the select the language of his choice (using a simple link), and make the entire site's text switch over to that language. I would prefer something similar to a language file, in which the values in the code are simply switched when the user selects his language. Below is a small example to illustrate what I am referring to.
<div class='title'>
[$siteTitleGoesHere]
</div>
I hope that makes sense. I am familiar enough with php and javascript that I might be able to use them to do this, if given direction. Thanks for any help.

Here's one approach..
Create a folder called lang
Inside this folder create your language files, lets say en.php and fr.php
These files contain an array called $lang that contains all the swappable text for your site.
for example in en.php
$lang['header'] = 'Welcome to my site!';
and in fr.php
$lang['header'] = 'Bonjour!'; // my french is awesome
You can then load the right file based on (for example) a session value
session_start();
if ( ! isset($_SESSION['lang'])) $_SESSION['lang'] = 'en';
require ("lang/{$_SESSION['lang']}.php");
echo $lang['header'];
If you wanted to change the language you could do something like this
in your php you will need to switch the session lang value to the new language
if (isset($_GET['lang']))
{
$_SESSION['lang'] = $_GET['lang'];
header("Location: {$_SERVER['PHP_SELF']}");
exit;
}
And you would use a link like this
French Language

Related

HTML lang Tag display language

I am asking this purely for educational purposes, while browsing for some reference information for HTML5, I came across the lang attribute, while I understand its a way of defining a language, if I were to say make a multi language site, rather than make every page again I would have assumed it would be a way to hide various divs based on the language of the browser i.e.
<div lang='en'>Hello</div>
<div lang='ja'>こんいちは</div>
So my first thought was if my browser was set to english it should show only the english tag, however upon further reading it seems that the lang tag only seems to tell the browser what language it is and added support for TTS, Braile, and other things.
Is this correct, or am I just being oblivious to some other underlying use of it?
If it is just a reader or something similar, would the best way of swapping languages on a single html/php site be:
<?php if ($_GET['lang'] == "en") { ?>
<div>Hello</div>
<?php } else if ($_GET['lang'] == "ja") { ?>
<div>こんいちは</div>
<?php } else { ?>
<div>Language not supported</div>
<?php } ?>
While I have been a programmer for many years, there are many small things like this that I have simply not come across before.
Regards
You could use CSS to show or hide elements depending on their lang attribute. You would just waste a lot of bandwidth.
Language Tag
The purpose of the language tag is to enable you to mark links, quotes or the like, so you can style them, e.g., add a british flag to a link that points to an English article from your Japanese blog post, and to enable screen readers to provide the correct pronounciation.
Translations
If you want to provide translated text depending on a parameter, you should do the translation outside of your HTML code (just like any other processing). The mix just makes code illegible and a maintenance nightmare.
A common solution is to provide translation data in separate language files, mostly .ini files. In your case, they could look like:
languages/ja.ini:
LANG="ja"
HELLO="こんいちは"
languages/en.ini:
LANG="en"
HELLO="Hello"
Now, you can use those in your HTML files.
index.php:
<?php
$language = $_GET['lang'] ?: 'en';
$translation = "languages/{$language}.ini";
if (!is_readable($translation)) {
throw new \RuntimeException("Language file {$translation} not found");
}
$_ = parse_ini_file($translation);
?>
<div lang="<?= $_['LANG']; ?>"><?= $_['HELLO']; ?></div>
Both your PHP and HTML code are easier to understand, and the language files are easy to maintain.

language link to pick correct language file

I have a two language setup, structured like this:
includes/languages/lang-it [has the defines]
includes/languages/lang-en [has the defines]
includes/languages/languages [has the languages array]
en/files
en/subs/files
it/files
it/subs/files
I have en/sub-1/index.php and en/sub-1/file-1.php and need to be able to change language when in file-1.php page
This is the code I have, and of course it does'nt work
require("../../includes/languages/lang-en.php");
link to file-1 English
link to file-1 Italian
Where LANG_ENG and LANG_IT are the directories (en and it)
So I need it to pick the includes/languages/lang-en.php for the the English, and includes/languages/lang-it.php for the Italian.
I guess I need to "require" the correct language file before "LINK-1", but don't know how.
I solved it like this:
Added $thispage, added variables for the file-name, and put that in the link.
Perhaps there are better ways, but that's what I could think of, and is working.
<?php require("../../includes/languages/lang-en.php");?>
<?php // variables for pages to use for language links
$file_1_en="file-1-en.php";
$file_1_it="file-1-it.php";
?>
<?php if ($thisPage=="page name")
echo'
'?>

Change language on the fly codeigniter

I have a welcome controller, which allows the user to choose a language (en or fr) which then points to it's respective controller (en or fr) so the url looks like this www.xxx.com/en/func/func. I would like so that there can be a link that can change the language, and I would like it to switch language but stay at the same page. Simply grab the corresponding language lines from the proper language files.
Which is the best way to do this?
You should use routing for this, in your routes.php you should add this:
$route['([a-z]{2})/(:any)'] = 'yourdefaulthomecontroller/$2/lang/$1'; // rearrange as you like
Then in your default controller you could find the rsegment and use it against whatever you need.
print_r($this->uri->rsegment_array()); // This will print out the routes
In practical:
if($this->uri->rsegment(3) == 'lang' && $this->uri->rsegment(4))
{
// Do something
}
the easy way is to add to your change language links variables you need to be saved after page reload
so look in your code for all navigation variables and simply add them to your language links
How do you currently achieve the I18N?
Whenever I deal with multiple languages on a site I use parser class as it allows to add multiple languages very easily.
By using that it is quite easy to switch languages by determining language requested in the url.
If by "on the fly" you mean changing the language without realoading the page then that's a whole other thing.

Dynamic site, using include to get content in specific div , how?

I want to use php to easily maintain my website, but I simply can't figure out the language - I've found some tuts online, and some other questions here, but none help me.
I've divided my site into some .php files, header/footer and such - And using
works fine..
Now I want the content of my site, to update according to which menu I click on at my site.
http://dawtano.com/pp/
If I click on "about" I want the "Hello World" to open inside my content div, but I can't get the right php code to do it.
I think you should do this---
Note: This will only work if the CSS styling are on the current directory! ()
<div>
<?php
$html_page = implode('', file('http://dawtano.com/pp/'));
echo $html;
?>
</div>
Hope this helps!
well currently your links are taking you to a separate page entirely. So why not just code it so that your include file is specific to the page. i.e, on about.php, use something like
include 'about_content.php
in your contetnt div.
If you're looking for your content to load dynamically into the content div you'll need to look into using ajax to fetch the content pages.
One popular way to construct the site is to have a single php script which displays content based upon a $_GET variable like 'page' or 'content', and then make the link as:
'http://dawtano.com/pp/index.php?page=helloworldcontent'
Using this method, you would need to check if the variable ($_GET['page']) is set using isset(), and then make sure the string is safe... as anybody with a browser could just type in some mumbo-magic script and hijack your site:
'http://dawtano.com/pp/index.php?page=somecleaverlycraftedhax'
Once it exists and is safe, add the '.php' to the file name and include that file... if it exists! If it doesn't exist, then you will need some code to handle that, probably by displaying a 'File not Found' message, or redirecting home, or something.
I prefer not to do this because it is a pain to make safe, and I feel like it is pretty ugly. What I do instead is put all the header/footer/navbar/title bar scripts into seperate 'display' functions, and put them in another file.
Then include this file with the function definitions, and call all the 'display' functions to set up the page. So every php script in your site might look like:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION, etc... */
print_html_pre_content();
print '<p>Hello, world!</p>';
print_html_post_content();
?>
Since every script will have this structure, you can just create a template file once. When you want to create a new page for your site, copy the template, rename the copy to the php filename you want, and add content between the two print functions.
You also keep the ability to modify the header/footer/navbar/title bar for the whole site in a central location, namely the included file with the functions.
You might be looking for some sort of Template Engine which allows you to create your pages out of variable parts. You could have a look at TBS, which is more or less what is suggested by the name. But there is a whole lot more engines out there which could do the job.
If that's already too much over the top, maybe Apache SSI (Server Side Includes) are a try for you.
A little suggestion from my side, I am often using Apaches mod_rewrite in connection with a single controller.php file. Apaches mod_rewrite will then send all request to the controller.php which will fetch the appropriate page parts for the requested page using TBS and return the respective page. So you have the controll of the page in one location only.
To your original question about.php could look like:
<?php
include('header.php');
?>
// original page content as html for about.php
// assuming header ends with the starting div <div> where you like the content to appear
// and footer starts with the closing div </div>
// if you need variable content here, simply use <?php echo $your_variable ?>
<?php
include('footer.php');
?>
The best way would be to use a switch statement:
http://php.net/manual/en/control-structures.switch.php
Something like this:
<?php
include("header.php");
$page = $_GET['page'];
switch($page)
{
case "about":
include "about.php";
break;
case "faq":
include "faq.php";
break;
case "help":
include "help.php";
break;
default:
include "home.php";
}
include("footer.php);
?>
Then just make all of your links look like this:
http://www.example.com/index.php?page=home
Just replace home with the correct page.

What's the best way (to avoid modifying repeated code) to build multilingual web pages

What's the best way (to avoid modifying repeated code) to building multilingual web pages?
I know how to build a multilingual web page without having to modify CSS and Javascript files.
But I can't think of a neat solution for HTML and Php files. Because if I have HTML or Php files for each language, I would have to modify each one if, for instance, I add an extra div or other element.
I was thinking to have something like this:
<div id="multilingual div">
<p><?php echo($multilingual-paragraph); ?></p>
</div>
(So, even if I modify these elements, I will just do it once, because the text that is in other language will show up from the variable).
I don't know Php, so I don't know how to tell Php to display a different variable according to the language (I think it has something to do with IF conditions)
Is this a good way of creating multilingual web pages or there are other methods?
(So with this
Check out the gettext() function. You don't really need to build different files for different languages. Altough, you'll have to struggle with the translation files.
You can implement a constants-solution for output messages. Using APC's cache functions, you can store multiple messages inside the cache and load them according to the pages you're viewing (this might not be an easy solution though, you need to know php for this).
This would allow you to maintain an array with values for each language in the cache. For example:
apc_constants_define('en',array('welcomeMessage'=>'Welcome!'));
apc_constants_define('es',array('welcomeMessage'=>'Bienvenidos!'));
apc_constants_define('de',array('welcomeMessage'=>'Willkommen!'));
through AJAX/select form, you can allow the user to choose the language they want to view your pages.
This language would be stored inside a session:
$_SESSION['language'] = 'en';
Next, on every page's top, you should check the session (simple switch statment) and load the constants from the cache accordingly.
apc_load_constants($_SESSION['language']);
then your html page would look like this:
<h1><?php echo welcomeMessage; ?></h1>
This is, as I see it, the most efficient way of internationalizing your website, and with an easily maintainable system, that doesn't require you to delve into the code when you want to translate your page to Romanian.
As you said, you have php and html language files, one way is to go like this:
$lang = '';
switch ($lang_file)
{
case 'en.php': $lang = 'whatever'; break;
case 'fr.php': $lang = 'whatever'; break;
// etc
}
<div id="multilingual div">
<p><?php echo $lang; ?></p>
// or you may include files
<p><?php include_once ($lang); ?></p>
</div>

Categories