how to change language in codeigniter - php

I've saved a product name in my DB with two language (En & Fr)
how can i load them differently by just changing the url
for example
localhost/mysite/en/products/
loads the "en_name" out of my table
and
localhost/mysite/fr/products/
loads the "fr_name" for me?

The language library is used if you want to store the text in different languages in a file (it will be included in the page) and not in a database. So if the language text is stored in the database, you want to check the method responsible for checking the url segment to check if the url contains the en or the fr and load the corresponding language.
So the method to use is:
$this->uri->segment(n)
More info on how to use it:
https://www.codeigniter.com/user_guide/libraries/uri.html
and your condition should be something like:
Edit
if($this->uri->segment(1) == "fr"){
$this->session->set_userdata('lang', 'fr');
}else{
$this->session->set_userdata('lang', 'en');
}
Now you can easily check for the language selected from the model (db files) by checking the value of the lang Session

I think the simplest method may be to pass the uri segment to the where clause of the query.
https://www.codeigniter.com/user_guide/libraries/uri.html
https://www.codeigniter.com/user_guide/database/query_builder.html?highlight=select#selecting-data
Something like:
$lang = $this-uri->segment(3);
$this->db->where('language', $lang);
$this->db->get('table');

i finally did it with this CI extension i18n and here is my code:
$lang = $this->uri->segment(1);
echo $prodct[$lang."_name"];
so now if i enter my url like this
localhost/mysite/en/products/
it will get those fields from DB which is like "en_name" ,
same goes for "fr" too.

Related

Selecting different languages from SQL database with PHP

I'm having a 2 issues with my website.
It's a multi language one (german, english).
I always kept the translations in an XML document like this
<?xml version="1.0" encoding="utf-8"?>
<root>
<les>
<en>Lesson</en>
<de>Lektion</de>
</les>
Then I converted those XML vars into php ones and echo'd them where needed like this
$xml=simplexml_load_file("langindex.xml") or die("xml not found!");
$les = $xml->les->$lang;
<?php echo $les;?>
Problem 1 is that no language is set as default when I open the Website so I always have to select a language first, even though I included that !isset. If I don't select anything, some images will be streched and it gives me the error that no language is set.
<?php
session_start();
$page = 0;
$lang = $_GET['lang'];
$langArray = array('en','de');
$found = false;
if(in_array($lang, $langArray))
$found = true;
if(!$found)
$lang = 'en';
if(!isset($_SESSION['lang']))
$_SESSION['lang'] = 'en';
if(isset($_GET['lang']) && in_array($_GET['lang'], array('en', 'de')))
$_SESSION['lang'] = $_GET['lang'];
include '../nihongo/php/dbconnect.php';
My language switch works with a simple <a href="?lang=X"> and that ?lang=X will be shown in the URL as well.
Enough of that.
Since XML is pretty inpractical I wanted to switch the whole thing up to an SQL database.
I've created a table with the columns ID, german and english and connected the db sucessfully.
Now I want PHP to tell SQL to get only the text of the session language with a select like this for example.
SELECT german FROM texts WHERE ID = '1'
SELECT english FROM texts WHERE ID = '2'
My problem is that I really don't know how to do that with PHP.
I would think that I'd either have to throw a PHP var into the statement somehow, or select the whole row and let PHP decide which one should be displayed.
Every advice/suggestion is welcome!
Thanks in advance!
I like the way OpenCart implemented this, because it's simple and doesn't add additional calls to the DB. Take a look at their implementation. You learn a lot investigating and learning from Open Source projects.
They have a php script per language and module with an array that contains all the strings. It just include or load the scripts to get access to the strings, for example: en-gb. Loading a string by its key with this method:
language->get('heading_title');

How to use $_GET variable (index.php?cat=about)

I know there must already has this question been asked but I didn't find the answer cause I don't know how to search exactly what I want.
So, I wanna make such a link http://example.com/index.php?cat=about where I should insert some about info. But I don't know how to make a page with this URL containing ? symbol and other stuff, or how to edit that page then, where to edit and etc.
About Us
I've also made cat.php file but what next?
In your index.php file you can use the following:
if(isset($_GET['cat']) { // means if the user use the url with ?cat=something
echo "<1>About {$_GET['cat']}</h1>"; //print the about of the cat as html
}
OK, Suppose you've two PHP files. page_a.php & page_b.php.
page_a.php
<?php
echo "<a href='page_b.php?cat=about'>Click Me</a>";
page_b.php
<?php
print_r($_GET); // Show all GET contents
echo $_GET['cat']; // Show what content exist in 'cat' part of url
Hope, this will clear your doubt of how to send data in url from one page to another using GET mehtod.
To store variable data in the url, you can use the query string. This is the portion of the url that immediately follows the protocol, domain name and file path
The query string begins with ? and may contain one or more parameter parameter value pairs. The parameter and parameter value are separated by =. Each pair is separated by &.
Let's suppose you do development for a tourism company called Gi Tours which provides content in 3 different languages. Because site visitors will want to be able to select their preferred language, you can provide flag images that will indicate a certain language and wrap those flags with the appropriate hyperlinks. Rather than writing out the full language name, you can simply assign id numbers to represent each like this:
<?php
echo "<img src=\"img/ge.png\">";
echo "<img src=\"img/en.png\">";
echo "<img src=\"img/ru.png\">";
?>
If a visitor clicks the second flag which loads this url: https://www.gitours.ge/index.php?lang=2, your index.php code can be written to extract the value assigned to lang by using $_GET["lang"].
If you write in your index.php file:
<?php
echo $_GET["lang"];
?>
Your code will display:
2
Or on your index.php file, you can easily generate dynamic page content using $_GET array data.
<?php
if(isset($_GET["lang"])){ // this checks if lang exists as a parameter in the url
$lang=$_GET["lang"]){ // $lang will equal the value that follows lang=
}else{
$lang=1; // if there was no lang parameter, this sets the default value to 1
}
if($lang==2){
// show English content
}elseif($lang==3){
// show Russian content
}else{
// show Georgian content
}
?>
This is, of course, a simplified demonstration; other techniques can be used to interact with the $lang value.
#Lasha Palelashvili let suppose below example:
above you are sending only one input parameter cat through url to the index.php file at server side so when you send this data from url it will send by get method by default, if you want to get this url info(input parameter) at the php side so $_GET will help you to fetch that info $_GET is actually an array which stores your input parameter as key and input parameter's value as value for your case("index.php?cat=about") $_GET array will contain value like below:
$_GET = array("cat" => "about")
now at the server side you can easily get the value like:
//index.php
<?php
$cat = $_GET["cat"];
echo $cat;
?>

How to get all languages data in codeigniter

I am trying to fetch all language files data and store them in array. But I am only able to get default language data.
I need all language data to sync them in another files. So far I have tried following code,
public function SyncJsLanguageFile($Language) {
//I need German (de) and other data as well data
$this->lang->load('translate','de');
//But I can only get default language data. So I think above line is not working.
$LanguageMessage = $this->lang->language;
echo "<pre>";
print_r($LanguageMessage);
die;
}
I don't want to change default language, I just need all language data in array for specific purpose. I should not change Site default language.
Please help me out here.
I have tried,
$data = $this->lang->load('translate','de', TRUE);
but it is not working. :(
Please do these steps
//load helper for language
$this->load->helper('language');
//mytest is the language file in english folder
//application\language\english\mytest_lang.php
$this->lang->load('mytest','english');// filename, folder name in
//fetch all the data in your custom $all_lang_array variable
$all_lang_array=$this->lang->language;
//display or test the data.
print_r( $all_lang_array);

how to make a multi-lingual php site?

I am developing a site using php and mysql. I want to know... what's a good way to deal with multi-lingual support? I want a user to be able to select from a drop down and select their language. Then everything (content, buttons, links) except the user-written content is in their language.
What's a good way to approach this? Use a cookie? Session?
Something like this works fine:
Langs.php
<?
// check if language switch as been set at url var
if ($_GET["lang_change"]) {
$_SESSION['session_name']["lang"] = $_GET["lang_change"];
}
// set value to lang for verification
$active_lang = $_SESSION['session_name']["lang"];
// verify $lang content and set proper file to be load
switch ($active_lang) {
case 'prt':
$lang_file = 'prt.php';
break;
case 'gbr':
$lang_file = 'gbr.php';
break;
case 'fra' :
$lang_file = 'fra.php';
break;
case 'esp' :
$lang_file = 'esp.php';
break;
case 'deu' :
$lang_file = 'deu.php';
break;
default:
$lang_file = 'gbr.php';
}
// load proper language file for site presentation
include_once ('$lang_file);
?>
LANG GBR FILE (gbr.php)
define("LANG_PAGETITLE_HOMEPAGE", 'Homepage');
define("LANG_BTN_KNOW_MORE", 'know more');
METHOD TO CHANGE LANGUAGE (url sample)
USE ENG
Basically, you have PHP files with constants, each file with a lang.
On click you set a url var (ex: lang_change = lang).
That will force page reload, and the langs.php file include at top of your index.php will load the selected language...
If you need more explanation about this, leave a comment and I'll send you a working sample!
Ps: session variables shown in this code is usefully for interaction with login systems, or just to avoid having the url parameters...
Save all dynamic content flagged with actual language
Make use of gettext() for buttons, etc. This one is much faster than including .php files with arrays
First of all you have to add all values in each language dynamically.
While adding dynamic content to your website, u can add languageId to each field of your tables in database. And then you can show that content at front end on behalf of that languageId.
I think it's a good idea to consider working with a framework that has internationalization support.
Take a look at this example using CakePHP http://bakery.cakephp.org/articles/view/p28n-the-top-to-bottom-persistent-internationalization-tutorial
I think the following will help you get some basic idea of developing it.
In a website, specially a multilingual website should have user interfaces / templates where hardcoded labels should be linked to variables. These variables should be loaded with correct language values. This can be done easily by including the language file containing the values in that specific language. You can have as many language files in a folder.
You will need to write a script in php, as whenever the user selects the language from the drop down, the page can reload with a language session. Another php script to fetch the selected language inside this session data and include the relevant language file inside the template/UI.
The same approach can be used in fetching content data from a table, where in all MySQL queries, you can use an additional lookup for language type from the content table. so that that file will be loaded.
SELECT * FROM posts WHERE lang='en' AND featured = 1
In many cases, the languages require HTML and CSS to be set accordingly to make the language render perfectly inside the browser. This means, you can also define language inside the HTML and in CSS define the fonts and directions (right to left or left to right).
I am recommending you to read the following in order to get more information on how to do it.
http://www.stylusinc.com/website/multilanguage_support.htm

Switching languages on a website with PHP

I'm just looking for some advice. I'm creating a website that offers (at least) 2 languages.
The way I'm setting it up is by using XML files for the language, PHP to retrieve the values in the XML nodes.
Say you have any XML file, being loaded as follows:
<?php
$lang = "en";
$xmlFile = simplexml_load_file("$lang/main.xml");
?>
Once the file contents are available, I just output each node into an HTML tag like so:
<li><?php echo $xmlFile->navigation->home; ?></li>
which in turn is equal to : <li>Home</li>
as a nav bar link.
Now, the way in which I'm switching languages is by changing the value of the "$lang" variable, through a "$_POST", like so:
if(isset($_POST['es'])){
$lang = "es";
}elseif(isset($_POST['en'])){
$lang = "en";
}
The value of the "$lang" variable is reset and the new file is loaded, loading as well all the new nodes from the new XML file, hence changing the language.
I'm just wondering if there is another way to reset the "$lang" variable using something else, other than "$_POST" or "$_GET". I don't want to use query string either.
I know I could use JavaScript or jQuery to achieve this, but I'd like to make the site not too dependable on JavaScript.
I'd appreciate any ideas or advice.
Thanks
I would go for session variable.
At the beginning of your pages you'll have:
if (!isset($_SESSION['language']))
$_SESSION['language'] = "en";
Then you'll have some links to change the language
Español
Français
Changelanguage.php simply is something like
$language = $_GET['lang'];
// DO SOME CHECK HERE TO ENSURE A CORRECT LANGUAGE HAS BEEN PASSED
// OTHERWISE REVERT TO DEFAULT
$_SESSION['language'] = $language;
header("Location:index.php"); // Or wherever you want to redirect
Have you thought about using $_SERVER["HTTP_ACCEPT_LANGUAGE"]? Something like this:
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"]) {
$langs = explode(",", $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
for ($i = 0; $i < count($langs); $i++) {
if ($langs[$i] == "en") {
$lang = "en";
break;
}
elseif($langs[$i] == "es") {
$lang = "es";
break;
}
}
}
Of course, a switch statement might fit a bit better here, and there's more ways to say English than only en, but this should work without the user having to do a thing. If they manually change, store it in a cookie as per Ben's answer.
The most common way would be to use it as part of the url and extract it when a page loads:
http://www.your-site.com/en/somepage
Are you using a framework?
The most common way to pass a language identifier is subdomain.
http://en.wikipedia.com/
both subdomains should point to the same directory and actual language can be easily extracted from the HTTP_HOST
and for storing language files the solution is gettext

Categories