How to Build a Language Switcher in PHP and JavaScript

When a user accesses your Web page, the PHP language includes a server function that you can use to detect the user's language. You use this detection along with JavaScript to create a language switching function that switches to another language section of your site when the user clicks a button. Typically, a user clicks a flag or language link on the page, and the browser redirects to your localized content.

Instructions

    • 1

      Right-click the PHP file you want to use to offer the language switching and click "Open With." Click your preferred PHP editor in the list of programs.

    • 2

      Create a variable that contains the language settings detected from the user. The following code retrieves the user's language:

      $language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

    • 3

      Print out the links dependent on the user's language settings. For instance, if the user's detected language is English, the following code creates an English link the user can click:

      if ($language == 'en-us') {
      echo "<a href=/en/index.php' onclick='switch(this.href)'>Click to switch to English</a>";
      }

    • 4

      Create the JavaScript function set up in the language link. In this example, the function's name is "switch()." Add the following script to switch the language:

      function switch(href) {
      window.location = href;
      }

Related Searches:

References

Comments

Related Ads

Featured