Search code examples
phplocale

Convert ISO 639-1 into a language name in local language with PHP


Stack Overflow offers some "similar" questions but none of them is suitable unfortunately. Or I am a bad searcher.

There is the language column in MySQL database which stores different ISO 639-1 codes depending on the user settings. Then I grab the user's ISO 631-1 code into the $lang variable and can output it with echo. No problem.

Is there a PHP 7 compatible technique to convert en into English, es into Español, fr into Français, etc?

I'm currently using the following code to achieve this

if($lang == 'en'){$userlang = 'English';}
if($lang == 'es'){$userlang = 'Español';}
if($lang == 'fr'){$userlang = 'Français';}

which I don't find optimal as there is a huge list of ISO 639-1 codes and I definitely don't want to put them all into the code.

Found locale_get_display_script manual at php.net but it returns nothing even copypasted from a given example - may be my ISP doesn't provide all required libraries. So I can't even check if it is what I am looking for. Anyway it doesn't look like this function can get ISO 639-1 codes.


Solution

  • Found locale_get_display_script manual at php.net but it returns nothing even copypasted from a given example - may be my ISP doesn't provide all required libraries.

    You can check it first before assuming that your provider doesn't support it. As far as my experience goes in PHP, if no class is installed, it will return an error, not "nothing".

    if (!class_exists('Locale')) {
        exit ('No php_intl extension installed.');
    }
    
    $userlang = Locale::getDisplayName($lang, $lang);
    
    var_dump($userlang);
    

    If you don't have any access, even just to install packages that already support ISO 639-1 via composer, you can use this script (using file_get_contents()) or download from my gist :

    $codes    = json_decode(file_get_contents('https://gist.githubusercontent.com/Kristories/f01f3d35d6ffbf3a3e2ee641b10e15e6/raw/d1b44ee63ff531ead9d27bc78e7815773fa706a4/ISO-639-1.json'), true);
    $userlang = isset($codes[$lang]) ? $codes[$lang] : false;
    
    var_dump($userlang);