Change the language of a site using a button

自闭症网瘾萝莉.ら 提交于 2019-12-13 01:14:00

问题


Hi I want as the title says change the language of the site using a button but this without altering the url mywebsite.com (Without doing mywebsite.com?lang=es) by just changing PHP variables in this code:

$xlang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);


if($xlang == "es")
{
$g_lang = "es";
}
else if ($xlang == "en")
{
$g_lang = "en";
}
else
{
$g_lang = "en";
}

And then using this button

<a class="langx" href="#"></a>

Change the language without altering the url

Is there a way to do that? if so, how?

Thanks in advance.


回答1:


You need to send the required value to the server when the button is clicked, so your link would have to have the language string like ?lang=es.

Then you can process it on the server side and store the language for the current visitor in for example a database (for logged-in users), a session or a cookie.

Then you can use a header redirect to redirect the user to the site without the language string and check at the top if the db-entry / session / cookie is set and use that language.




回答2:


While you can handle the request dynamically, you need to provide another method, and here's why. According to Google if you care anything about SEO, you'll want to Make sure the page language is obvious. You can do the hat trick on the fly and switch the language via language preferences, but you also need to provide a link to a page that is always in the other language if you expect to get any traffic in that language from search engines.

If this page dynamically detects the language, then whatever language Google sees when it crawls is the language it will make the page as.

http://www.example.com/

If the site contains a query string flag for another language the site is likely to be crawled in both languages IF there is a link to the second language somewhere on your site. These are good examples (a separate domain is the best option) for showing Google where a Spanish page would reside.

http://es.example.com - best for SEO

http://www.example.com/?lang=es

http://www.example.com/es/

In your PHP code you're only catching the initial 2 digit code for the preferred language of the browser. Some people actually read in more than one language (basically anyone who's not American). They might have those other languages in their preferred languages, so while someone from France may have fr as their preferred language, they may also understand English (en), so their browser accepted string might look something like this in Chrome:

fr,en-US;q=0.8,en;q=0.6

or this in IE:

fr-FR,en-US;q=0.5

This code will check to see if they've set the $_GET flag for the language and override the automatic translation. I found this code, then modified it to work for my purposes because the site where it's being used is European where most people speak multiple languages. For this code I've modified it here, so if their preferred language isn't Spanish it will default to English. This would go into a file like lang.php which would get included on every page.

<?php
$langs = array();
if (!empty($_GET['lang'])){
    $tempLang = $_GET['lang'];
        //Setup the switch for all of the possible languages.
    switch($tempLang){
        case 'es':
        $pref='es';
        break;
        default:
        //english
        $pref='en'; 
    }

} elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    // break up string into pieces (languages and q factors)
    preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

    if (count($lang_parse[1])) {
        // create a list like "en" => 0.8

         $langs = array_combine($lang_parse[1], $lang_parse[4]);

        // set default to 1 for any without q factor
        foreach ($langs as $lang => $val) {
            if ($val === '') $val = 1;
        $lParse = strtolower(preg_replace('!\-.*$!','',$lang));
            if(!isset($newLangs[$lParse])){
                $newLangs[$lParse] = $val;
            }

        }

        // sort list based on value 
        arsort($newLangs, SORT_NUMERIC);
    }

//Set the preferred languages for the website (available translations)
$preferred = array('en','es');

//Check for overlap keeping the preference order
$intersect = array_values(array_intersect(array_keys($newLangs), $preferred));

//print_r($newLangs);

if(isset($intersect[0])){
    //Set the first preference
    $pref = $intersect[0];  
    if(preg_match('!^es!',$pref)){
        $pref='es';
    }   
} else {
    //default to english
    $pref = 'en';   
}


} else {
    //default to english
    $pref = 'en';   
}

?>

On the page including lang.php you would need to check the $pref variable to show the proper translation for the language.

Javascript

You can do a redirect with Javascript to make the page load the other language using this same code, however search engines typically only look at Javascript for exploits and won't follow the links in the Javascript. According to Google Webmaster's Guidelines:

Use a text browser such as Lynx to examine your site, because most search engine spiders see your site much as Lynx would. If fancy features such as JavaScript, cookies, session IDs, frames, DHTML, or Flash keep you from seeing all of your site in a text browser, then search engine spiders may have trouble crawling your site.

You can do the change with a click using AJAX, however the URL where AJAX would listen would need to be passed the parameter and these are usually passed via $_GET variables.

IP Look-up

Another method some people have tried is to check the IP address and reverse look-up the location to see where the country of origin is, then they'll pick the national language. The problems with this are:

  1. People travel
  2. Some IP addresses are registered to owners in other countries (think corporate blocks) rather than the country where the user is browser.
  3. Some of the IP address listings are highly inaccurate.

Cookies

Not all users accept cookies and some corporate firewalls may even strip the cookies.




回答3:


i don't understand what do you need to do exactly , but i think you want to refresh a page to apply changes when you click the button without adding anything to your url ! if i'm right , you can use Jquery location.reload() function like this :

// don't forget to add link to jquery file for example : <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">

  $(document).ready(function(){
   $('.langx').click(function() {

          location.reload();

   });
  });

</script>

personally i use gettext library to translate my website: i make a list of languages and then i use ajax call to send what user are choosing as language and if translation for this choice is available i return ok and finally i reload the page with js. you can learn about gettext lib or check documentation here

if this is not what do you want, please add more details to render clear your question



来源:https://stackoverflow.com/questions/17119160/change-the-language-of-a-site-using-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!