Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My site have an folder language where have:
en.php
<?
$lang = array(
'sp1' => 'Welcome',
'sp2' => 'Home',
);
?>
and it.php
<?
$lang = array(
'sp1' => 'Benvenuto',
'sp2' => 'A casa',
);
?>
In the index.php i have like:
<h4><?=$lang['sp1']?></h4>
<a><u><strong><?=$lang['sp2']?></a></u></strong><br />
But this is an option for change the language from cpanel, how I can transform to the geo language.. when an italian visit my site can view my site in italian language, etc?
You can use $_SERVER['HTTP_ACCEPT_LANGUAGE']
<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
case "fr":
//echo "PAGE FR";
include("fr.php");
break;
case "it":
//echo "PAGE IT";
include("it.php");
break;
case "en":
//echo "PAGE EN";
include("en.php");
break;
default:
//echo "PAGE EN - Setting Default";
include("en.php");//include EN in all other cases of different lang detection
break;
}
?>
Browsers advertise the user's "preferred" language in an HTTP header called Accept-Language, which you can read in PHP as $_SERVER['HTTP_ACCEPT_LANGUAGE'].
There is actually a fairly complex structure to this header, allowing multiple languages to be given priorities, and the language itself can take a few different forms. The answers to this previous question discuss how to parse it fully.
But as a first approximation, you can just take the first two letters, which will generally be one of the ISO 639-1 codes listed here by the US Library of Congress or here on Wikipedia:
$default_language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
However, this should never be the only way of selecting the language. As explained fairly clearly by this W3C document, the browser might not be correctly configured, or the user might not be using their own computer, so that it would not be sending the correct value.
Instead, you should treat this as a default, and allow the user to over-ride it. This can be as simple as providing links on every page which add ?lang=it (etc) to the current URL. Then set a cookie containing their preference, and ignore the accept-language from then on:
if ( $_GET['lang'] ) {
// User asked for a particular language; obey, and remember in a cookie
setcookie('lang', $_GET['lang'], 0, '/');
$preferred_language = $_GET['lang'];
} elseif ( $_COOKIE['lang'] ) {
// Cookie found from previous selection
$preferred_language = $_COOKIE['lang'];
} else {
// Guess based on browser settings
$preferred_language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have created a custom router. For Example
$istek = $_SERVER['REQUEST_URI'];
switch ($istek) {
case '/' :
$title = "Anasayfa";
require base . 'views/index.php';
break;
So I want to pass the example id variable with $_GET. But the router blocks it and redirects to the 404 page. how can I pass this variable without getting any errors or redirecting to 404?
The reason is that $_SERVER['REQUEST_URI'] includes everything, not just the / so your switch will fail.
To fix, use parse_url, / is the PHP_URL_PATH, whilst ?id= would be in PHP_URL_QUERY.
So you could use something like this to get what you want from $_SERVER['REQUEST_URI']:
<?php
// example
$_SERVER['REQUEST_URI'] = '/controller/action?id=123';
$uri = $_SERVER['REQUEST_URI'];
$uri = parse_url($uri);
$route = explode('/', ltrim($uri['path'], '/'));
print_r($route);
parse_str($uri['query'], $query);
print_r($query);
Result:
Array
(
[0] => controller
[1] => action
)
Array
(
[id] => 123
)
https://3v4l.org/UMFQF
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
What is the best way in smarty to create a function to parse a name?
example:
I have the variable {$attachment.filename}
If the file name is .jpg|.jpeg|.gif|.png
--- my result --- (option to open in lightbox... else no option to open in lightbox...)
Thanks!
Do the parsing in PHP and set a flag in a Smarty variable. In the template check the flag and display what you need. Don't embed logic in templates.
If you really need this functionality in many templates you can, indeed, write a Smarty plugin that suits your needs.
The documentation about Smarty plugins includes examples that can inspire you.
For example:
// Define the function that implements the plugin
function my_special_img($params, Smarty_Internal_Template $template)
{
$src = $params['src'];
// Based on $src decide here if you want lightbox or not
$lightbox = TRUE; // or FALSE
// Generate the <img> element
// Get information from $params, put default values, do whatever you want
$output = implode(' ', array( // build the string from pieces
'<img',
'src="{$src}"',
'width="{$params['width']}"',
'height="{$params['height']"',
'alt="{$params['alt']}"',
'class="{$params['class']}"',
($lightbox ? 'rel="lightbox"' : ''),
'/>'
));
// Smarty will replace the function call in the template with the value it returns
return $output;
}
// Register the plugin in Smarty
$smarty->registerPlugin('function', 'image', 'my_special_img');
In the templates, replace
<img src="filename.jpg" width="40" alt="bla-bla" etc>
with
{image src="filename.jpg" width="40" alt="bla-bla" etc}
That's all. Express your creativity in the plugin's code but keep it simple and use only the values provided in $params.
This question already has answers here:
Create a webpage with Multilanguage in PHP
(10 answers)
Closed 9 years ago.
Alright, so I'm forced to create a multi-language support site in 4 languages (Greek, French, English and German). I have some ideas on how to set it up, although I would like a second opinion on this.
The first option is to include the file based on the user's settings.
/*
------------------
Language: English in ENGLISH.PHP
------------------
*/
$lang['TITLE'] = 'My website page title';
$lang['HOME'] = 'Home';
/*
------------------
Language: French in FRENCH.PHP
------------------
*/
$lang['TITLE'] = 'Titre site-web';
$lang['HOME'] = 'Accueil';
The file would be included accordingly: include_once 'ENGLISH.PHP'; etc.
The other option is to create one general file, but have the language output in an array:
$lang = array("en"=> array("TITLE"=>'My website page title',
"HOME" =>'Home'),
"fr"=> array("TITLE"=>'Titre site-web',
"HOME" =>'Accueil'));
$set = $USER_INFO->langPref(); // output: en, fr, gr, de
echo $lang[$set]['TITLE'];
The second option seems easier to manage, but I'm not sure if there are any drawbacks to this method...
Any opinions?
By the way, I was planning on translating everything myself.
Don't waste your time, use a framework, Symfony2 for example has a excellent internationalization component:
http://symfony.com/doc/current/components/intl.html
or CakePHP, even easier =)
http://book.cakephp.org/2.0/en/core-libraries/internationalization-and-localization.html
but...if you really...really want to do from scratch =) I recommend you to use something like .po files, here you are some article that could help; http://www.icanlocalize.com/site/tutorials/how-to-translate-with-gettext-po-and-pot-files/
I strongly recommend the use of a framework or even a CMS has this functionality built in...
I hope this can help.
You can used .ini to store language:
set = $USER_INFO->langPref();
if(file_exists("PATH_TO_FOLDER_LANGUAGE/".$set.'.ini')){
$arrLanguage= parse_ini_file("PATH_TO_FOLDER_LANGUAGE/".$set.'.ini');
}else{
$arrLanguage = array();
echo "Language file not found";
}
print_r($arrLanguage);
in ini file, it will be same:
TITLE=Titre site-web
HOME=Accueil'
read more about init file at here: http://en.wikipedia.org/wiki/INI_file
Hope it can help you!
I have managed to make my URL i18n compliant using Zend_Controller_Router.
Ie:
en/user/login becomes fr/utilisateur/connexion and both URLs go to the same controller/action.
The problem I am facing is the following
I have a language switcher that is displayed as follow :
Français
English
Italiano
etc.
The currently active language doesn't have an anchor tag, but all others do.
For the languages that have an anchor on them I am building the URL and I want them to be translated in their specific languages.
Currently if I am in French all the urls get builded in french, even if I set the #local key as a param in the URL view helper (tried "#locale" => 'en', "#locale" => new Zend_Locale('en'))
en/utilisateur/connexion
it/utilisateur/connexion
instead of
en/user/login
it/utente/collegamento
because the locale used while building the URL is the one that is defined application wide.
EDIT
I digged a bit deeper in my issue an I found that only the current locale add its resources loaded, which mean I can't get route in the proper language for the route to be built in the right language
My new issue is : how do I load multiple language translation resources?
(I am planning to implement cache in the far future (near release), so I might get better performances)
Hope this helps re the new issue.
"My new issue is : how do I load multiple language translation resources?"
Just a quick caveat to say I didn't write the code below, it was taken from a example app put together by the guys at Zend however it might help to have it broken down like this.
Their approach for the example app was using a csv file containing translations and using your config file (the default one in a new project being application.ini) to specify the path to all your language translation resources.
like this:
;; Languages
language.file.en = APPLICATION_PATH "/../language/en/translate.csv"
language.file.fr = APPLICATION_PATH "/../language/fr/translate.csv"
language.file.de = APPLICATION_PATH "/../language/de/translate.csv"
language.file.es = APPLICATION_PATH "/../language/es/translate.csv"
language.name.zz = Language
language.name.en = English
language.name.fr = Français
language.name.de = Deutsche
language.name.es = Español
And in each csv file, if you are using something like Excel or Open Office to create it, column A would be the original language and column B the translation.
As an example where English is the original language and a Spanish translation is required:
A B
login entrar
logout salir
You could do that for all the words/phrases you want to translate.
If a translation isn't found then the default original word is used.
Your main application bootstrap could have something like this:
protected function _initLanguage()
{
$options = $this->getOptions();
Zend_Registry::set('language',$options['language']);
$langSess = new Zend_Session_Namespace('language');
if (!isset($langSess->translate)) {
$translate = new Zend_Translate('csv', $options['language']['file']['en']);
$langSess->translate = $translate;
}
if (!isset($langSess->locale)) {
$langSess->locale = 'en';
}
Zend_Locale::setDefault($langSess->locale);
}
As the translate object is held in the session you can use it in any of your views etc using something like:
$langSess = new Zend_Session_Namespace('language');
$translate = $langSess->translate;
and:
<?php echo $translate->_('login') ?>
where you want something to be translated on selecting an alternative language. In the example above the word login would appear when English is selected and entrar when Spanish is selected.
There's loads more to Zend_Translate than this and several ways to implement it so I'm not saying this is the best way by any means.
If it helps or if I can give you more info let me know.
Cheers,
Dave
I'm posting this question on it's own as I found post one which lacks full explanation or the best way to do it.
Should I use a language file to name items like:
$first_name= 'name';
$last_name = 'last_name';
and then include this file depending on selection?
I have an app which I need to have in two languages.
Will like something in this lines:
http://www.myapp.com/?lang=en
http://www.myapp.com/?lang=es
Should I use a constants file for this purpose?
constants.php
define('OPERATION_NOT_ALLOWED_EN', 'This operation is not allowed!');
define('OPERATION_NOT_ALLOWED_ES', 'This operation is not allowed!');
What is the recommended way of accomplishing this?
You can follow in the footsteps of phpBB - they use a $lang[] array with code that looks like:
$lang['Next'] = 'Next';
$lang['Previous'] = 'Previous';
$lang['Goto_page'] = 'Goto page';
$lang['Joined'] = 'Joined';
$lang['IP_Address'] = 'IP Address';
$lang['Select_forum'] = 'Select a forum';
$lang['View_latest_post'] = 'View latest post';
$lang['View_newest_post'] = 'View newest post';
$lang['Page_of'] = 'Page <b>%d</b> of <b>%d</b>'; // Replaces with: Page 1 of 2 for example
$lang['ICQ'] = 'ICQ Number';
$lang['AIM'] = 'AIM Address';
$lang['MSNM'] = 'MSN Messenger';
$lang['YIM'] = 'Yahoo Messenger';
It is of course included from a file specified in the user's settings, but you'd be fine with your suggestion of ?lang=en in the query string accessing something similar to a constants.php file.
You might want to name the file lang_en.php or something similar for clarity.
That will work for strings like you gave in your example. But there are other complications. For example, do you want to format dates in the appropriate format for the locale (es vs en?). How about formatting of numbers and currencies? Also, you might have "dynamic" messages: "You have $x messages in your inbox". Where you want to pass variables. Check out some of the php localization libraries. Here is an online tutorial: http://www.devx.com/webdev/Article/38732.
Also look at the framework you are using. Many of them have localization support.
How should you implement it? Like Zend_Translate.
I would use locale-specific files with constants, eg:
locale_en.php:
define('GREETING', "Welcome to Widgets Inc');
and
locale_de.php:
define('GREETING', 'Wir begruessen Sie zu Widgets Inc');
in your setup you detect the locale and do:
if ($locale == 'en') {
require 'locale_en.php';
} else if ($locale == 'de') {
require 'locale_de.php';
}
This gives you the benefit of constants and makes localization reasonably transparent to your application in that you don't have to do if ($locale ... all over the place. If anything is locale-specific, just put it in the locale files.
If you want to add a locale file just copy an existing one and change all the references rather than trawling your codebase for them.
You can also put code in these files like correctly formatting numbers and dates for these locales (including the right names in each language but also the use of commas, quotes, periods and so on), currency conversions and displays, etc.
There are free 3rd party controls to do this using an ISO standard XML file (I wrote a database utility to create, edit & export into this format).
The other answers are very manual and involve more work than using this control does.
The control you need is found at:
http://ezcomponents.org/docs/api/trunk/introduction_Translation.html
After the eZ Components are installed on the server, you need to retrieve the base control required for all eZ Components
require_once "ezc/Base/base.php";
/**
* __autoload()
*
* #param mixed $className
* #return
*/
function __autoload( $className )
{
ezcBase::autoload( $className );
}
Then you must define where the XML language file is located (see: ISO639-2, ISO3166, and Qt Linguist)
$config["language_code"] = "en_us"; // as defined by ISO639-2 and ISO3166
// grab our translation XML file
$backend = new ezcTranslationTsBackend( dirname( __FILE__ ). '/translations' );
$backend -> setOptions( array( 'format' => $config["language_code"].'.xml' ) );
// create a manager object
$manager = new ezcTranslationManager( $backend );
$language = $manager->getContext( $config["language_code"], 'strings' );
now you can grab strings by simply calling the following function
getTranslation( "SOME_KEY" );
and to retrieve phrases that have parameters use the following syntax, please note the relation between [KEYWORD] and "keyword" is intentional and recommended
getTranslation( "FIND_[KEYWORD]_BY_[TYPE]", array("keyword" => $keyword, "type" => $type ) );
an example of a TS XML file is (should be called en_US.xml)
<!DOCTYPE TS>
<TS>
<context>
<name>strings</name>
<message>
<source>ZONE_TYPE</source>
<translation>Zone Type</translation>
</message>
<message>
<source>ZONE_TOOL</source>
<translation>Zone Tool</translation>
</message>
<message>
<source>HELLO_[NAME]_WELCOME_TO</source>
<translation>Hello, %name, welcome to Webfood Admin</translation>
</message>
<message>
<source>YOUR_ADMINISTRATIVE_SESSION_HAS</source>
<translation>Your administrative session has timed out. Please login again.</translation>
</message>
</context>
</TS>
I would simply have a setting, in your PHP sessions, that stores the language used, perhaps ask the user before or after they log in which language they want, and store it to their user table if you have accounts. There's no reason to keep sending a URL value over and over, that's a bad idea.