Multilanguage support PHP [duplicate] - php

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!

Related

Typo3 getting data and convert it to specific xml schema

i am new to typo3, so sorry, if this is too obvious.
I do not expect a complete solution, just the topics i would need to read about in order to solve the task would be perfectly enough. :)
Here the task:
I have a typo 3 installation with job advertisements in it. Now the company wants to publish that data in to a social website, which needs to have the job advertisement data put on a server in an xml feed, which looks like this: http://www.kununu.com/docs#jobfeed. Don't worry about what it says in there, it's just stuff like Job Title, Description etc.
Like i said, i am completely new to this and just have a vague idea.
My thoughts so far were something like this:
I probably need to write a plugin, which pulls the data out of typo3 by the push of a button
That Plugin need to establish a database connection to pull the data (probably it's mysql, but i am not entirely sure yet)
The data need to be formatted, which is either done by some string operations or by some kind of xml handler i assume.
Sidenote: I read something about TypoScript, but i'd like to avoid that, since it's a one time project and probably not worth the time to learn it. For me at least.
Thank you loads for your help in advance.
Cheers
you can handle that (basicly with typoscript). The other part has to come from PHP (F.e. extbase plugin) ... First part creates the XML output. Second part uses my Demo plugin to include data (Pages+special fields) from DB.
Within TS we are able to create a new typeNum. With that you can call your XML. ( ?type=1234 ) Within the BE you can select each page for output.
If you need help just contact me. I would send you the plugin.
sitemap = PAGE
sitemap {
typeNum = 1234
config {
# Set charset to utf-8
metaCharset = utf-8
# Deactivate TYPO3 Header Code
disableAllHeaderCode = 1
# Content-type settings
additionalHeaders = Content-type:text/xml;charset=utf-8
# Do not cache the page
no_cache = 1
# No xhtml cleaning trough TYPO3
xhtml_cleaning = 0
}
10 = USER_INT
10 {
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
pluginName = Sitemap
extensionName = Srcxmlprovider
controller = Sitemap
vendorName = Sourcecrew
action = exportXml
switchableControllerActions {
Sitemap {
1 = exportXml
}
}
}
}
Ich habe die EXT noch schnell ins TER gepushed. Ein Tutorial liegt innerhalb.
http://typo3.org/extensions/repository/view/srcxmlprovider

Drupal 7 - Page template suggestion based on specific alias

I'm poor php developer and i need code for my template.php to set specific template for some pages:
Example:
mypage/blog/about-me
mypage/blog/about-you
mypage/blog/about-us
Uses page--blog-about-first.tpl.php.
mypage/blog/about-him
mypage/blog/about-her
mypage/blog/about-them
Uses page--blog-about-second.tpl.php.
I can't find it anywhere so i'm asking here.
Check the naming conventions here:
https://drupal.org/node/1089656
If you need to do something more complex you can use the instructions here/:
https://drupal.org/node/223440#custom-suggestions
// Page template suggestions based off URL alias
$alias=drupal_get_path_alias($_GET['q']);
$args=explode('/', $alias);
if ($args[0]=='blog/about-me') {
$vars['theme_hook_suggestions'][] = 'page__simple_blog';
}
elseif ($args[0]=='artist') {
$vars['theme_hook_suggestions'][] = 'page__simple_blog';
}
This is the code. I got link /blog/about-me and link /artist. Suggestion works for artist page, but not for blog/about-me. Solution?

Smarty assign var to config file vars

My question looks almost the same as this Is it possible to put variables inside config files?
I have a config file that controls the language. Also I have a feedback div that is showed for the feedback.
Now I want to assign feedback like this:
$smarty->assign('feedback', 'the_age_of_user_' . $user->name . '_is_changed_to_' . $user->age . '_years');
nl.conf
the_age_of_user_%s_is_changed_to_%s_years = De leeftijd van gebruiker %s gewijzigd naar %s jaar
en.conf
the_age_of_user_%s_is_changed_to_%s_years = The age of user %s is changed to %s years
Does anyone know how I can accomplish this? Or is there a better solution to assign variables to the config file?
Sorry, but I don't completely understand what are you trying to accomplish.
In our project, we have following solution for similar problem:
Language file:
the_age_of_user_is_changed = The age of user {user} is changed to {year} years
Notice that there is no %s or any variables on left side. It is always constant.
Option 1:
Smarty/code assigment:
$smarty->assign("VARIABLE_TO_USE_IN_TEMPLATE", getLang('the_age_of_user_is_changed', array('user' => $user->name,'year' => $user->age));
Then, in Smarty, you can use following code: {$VARIABLE_TO_USE_IN_TEMPLATE}
Function getLang reads string information from language files and replaces all {symbol} to corresponding data.
Option 2:
In template, we have smarty userspace function:
{LANG key='the_age_of_user_is_changed' name=$user->name year=$user->age}
Lang is actually calls function getLang from previous example.
In code you have to assign user: $smarty->assign("user", $user);. After that, smarty will do everything by itself.

Zend translate URL and language switcher

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

How to Implement multi language in PHP application?

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.

Categories