0

I create a multilingual website and I am wondering how to get the language data. Well, my code gets information about the user's language from the browser, then include the locale file.

get user language:

<?php
$hl = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
?>

include locale:

<?php
if (file_exists('locales/".$hl.".php')){
  include "locales/".$hl.".php";
}else{
  include "locales/en.php";
}

/*    VS    */

switch ($hl){
  case 'de': include "locales/de.php"; break;
  case 'fr': include "locales/fr.php"; break;
  /* ...*/
  default: include "locales/en.php";
}
?>

Which way is the best?

  • 2
    The first will be much shorter with many languages, I would use that. – AbraCadaver May 08 '18 at 18:01
  • You might find some info in my post helpful. It retrieves language from a fall-through pattern: from URL, session, browser, fallback. https://stackoverflow.com/questions/49756515/multiple-language-via-session-two-directories?answertab=votes#tab-top – waterloomatt May 08 '18 at 18:42

1 Answers1

0

There are many ways to approach this, and depends on numerous things we don't know about in your code. For example, is locales/en.php always available (ie doesn't need an file_exists() check). etc etc

Even then it's arguably personal opinion what is best.

Personally, for clean and simple but not over the top, I prefer:

$hl = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
file_exists('locales/'.$hl.'.php')
    ? include 'locales/'.$hl.'.php'
    : include 'locales/en.php';

But again is up to you and what makes sense for your requirements and other coding style. E.g. if it'd be useful to reuse the value for the determined language (eg "EN" or the value which came from the server variable eg "DE") then this would be better:

$hl = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$language = file_exists('locales/'.$hl.'.php')
    ? $h1
    : 'en';
include 'locales/'.$language.'.php';

// $language can be used again, eg echo "currently viewing in {$language}";

You could tighten it up more, but careful it doesn't head towards being unclear.

$browserLanguageFile = 'locales/'.substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2).'.php';
file_exists($browserLanguageFile)
    ? include $browserLanguageFile
    : include 'locales/en.php';
James
  • 4,644
  • 5
  • 37
  • 48