Skip to content
Advertisement

In Firefox my Text displays perfectly but Chrome says offset in PHP

I have a function in my PHP script which loads the correct localization file based on the locale, which the header sends. In Firefox my Text is displayed perfectly, but when I switch to Chrome it only says “Notice: Trying to access array offset on value of type null in [PATH]/index.php on line 46”

My function to load the language is this one:

<?php

/**
 * This function loads the specified language by their locale identifier
 * 
 * @param string $locale The locale identifier
 * @param string $page Page to load data for
 * @return array Returns array with data
 */

 // Example Code snippet on how to use it:
 /*
$locale = locale_accept_from_http($_SERVER["HTTP_ACCEPT_LANGUAGE"]); // Locale retrieved from Header

$language = loadLanguage($locale, "panel"); // Loads the language for the "panel" Page

 */
function loadLanguage($locale, $page){
    $langlist = [
        "de",
        "en"
    ];
    $lang_values = array_values($langlist);
    if(in_array($locale, $lang_values)){
        if(file_get_contents(dirname(__FILE__) . "/{$page}" . "/snippets_" . strtoupper($locale) . ".json")){
            return json_decode(file_get_contents(dirname(__FILE__) . "/{$page}" . "/snippets_" . strtoupper($locale) . ".json"), true);
        } else {
            return json_decode(file_get_contents(dirname(__FILE__) . "/{$page}" . "/snippets_EN.json"), true);
        }
    }
}

?>

The translation files for German (de) and English (en) exist in their folders so I don’t really understand, why it doesn’t work. Does Chrome even send the language header?

Thanks for your help tho!

Advertisement

Answer

My Chrome browser sends “en-GB,en-US;q=0.9,en;q=0.8” for HTTP_ACCEPT_LANGUAGE from the UK

When passed into locale_accept_from_http you get “en_GB” .. not “en”. You either need to allow for GB and presumably en_US etc, or maybe substring the result to the 1st 2 language characters.

Note that its totally possible that the header wont be sent for a given browser so you should check default to one or the other languages is a match isn’t found. the function returns NULL if not found. You could also have another country returned obviously.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement