La solución para php setlocale [solved]



Un gran problema que los desarrolladores se topan siempre cuando quieren tropicalizar o adecuar el idioma de su script es que la función setlocale "setlocale()"de php no funciona o no devuelve el false pero no hace el cambio deseado de idioma. 

Veamos el manual de php (php.net) nos comenta que hay que colocar la constante de la categoría como su primer parámetro: 

  • LC_ALL para establecer todas las siguientes
  • LC_COLLATE para la comparación de cadenas; véase strcoll()
  • LC_CTYPE para la clasificación y conversión de caracteres, por ejemplo strtoupper()
  • LC_MONETARY para localeconv()
  • LC_NUMERIC para el separador decimal (véase también localeconv())
  • LC_TIME para el formato de fecha y hora con strftime()
  • LC_MESSAGES para las respuestas del sistema (disponible si PHP fue compilado con libintl)
Y su segundo parámetro es colocar una cadena de texto un array en el cual se colocan parámetros para probarlos como localismos hasta que se tenga éxito, y aquí es donde comienza la pesadilla o el problema para todos. 

Pues el problema es de que no todos los servidores tienen instalados estos localismos que deseamos o no conocemos sus valores o cómo representarlos y podemos toparnos con este problema sin encontrar solución. 

También otro problema es de que windows y linux utilizan diferentes valores, así como WAMP y XAMP, entre otros... ¿Y como lograr saber estos valores y saber cuales están instalados?
 
Esta es la solución que "trovista" nos ha dejado para solucionar este problema: 
 
$language: using system('locale -a | grep -i $code')";
    echo "

The available 'locale' strings for '$code' on this server are:

";
    echo "
";
    system("locale -a | grep -i $code");
    echo "
";
}

function check_locales($test_names, $language)
{
    echo '

';
    echo "

$language

";
    foreach ($test_names as $value) {

        echo '

';
        echo "

Trying: '$value'

";
        $locale_found = setlocale(LC_TIME, $value);

        if ($locale_found) {
            echo "

locale '$locale_found' found for '$value'. "; echo 'eg.: ' . strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 23, 1978)) . '

';
        } else {
            echo "

No locale found for '$value'

";
        }
    }
}

?>



    
     Server - Test
        Locales

Testing Locales

In this script are defined lists of possible locales for both Windows and Unix-based servers. The tests will try them all to show the possible values to use for LC_TIME on this server in the main language file.

UNIX server

WINDOWS server

It is possible to get a listing of all the installed locales in Windows with the Windows Powershell (requires .net), as detailed here:

Open Windows Powershell console, eg: PS C:\Users\Steve>

Enter the command as shown to get the listing:

[System.Globalization.Cultureinfo]::GetCultures('AllCultures')

To be clever and get a csv file of this full listing (change the destination as required), use this set of commands on one line (the semicolons concatenate the commnds):

Function global:GET-CULTURE { [System.Globalization.Cultureinfo]::GetCultures('AllCultures') }; $locales=GET-CULTURE; $locales | EXPORT-CSV D:locales.csv

See the references at the foot of this page to go some way towards convincing you to dump your Windows-based hosting and it's lack of support for utf-8:

Quote from Microsoft here.

"The locale argument can take a locale name, a language string, a language string and country/region code, a code page, or a language string, country/region code, and code page. The set of available locale names, languages, country/region codes, and code pages includes all those supported by the Windows NLS API except code pages that require more than two bytes per character, such as UTF-7 and UTF-8.
If you provide a code page value of UTF-7 or UTF-8, setlocale will fail, returning NULL."


Resources

PHP setlocale: http://php.net/manual/en/function.setlocale.php

Guide to getting PHP, utf-8 and mysql to play together: https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql

UTF-8 background: http://htmlpurifier.org/docs/enduser-utf8.html

Character sets: http://www.phpwact.org/php/i18n/charsets

Table of locales/codepages: https://docs.moodle.org/dev/Table_of_locales

The Wacky World of Windows

http://stackoverflow.com/questions/10995953/php-setlocale-in-windows-7

Table of Locales: http://www.science.co.il/Language/Locale-codes.asp#definitions

Globalization Step-by-Step: https://msdn.microsoft.com/en-gb/goglobal/bb688113.aspx

Windows Country/Region Strings: https://msdn.microsoft.com/en-us/library/cdax410z(v=vs.140).aspx

Windows Language Strings: https://msdn.microsoft.com/en-us/library/39cwe7zf.aspx

National Language Support (NLS) API Reference: https://msdn.microsoft.com/en-us/goglobal/bb896001.aspx

Locale IDs, Input Locales, and Language Collections for Windows XP and Windows Server 2003: https://msdn.microsoft.com/en-us/goglobal/bb895996.aspx

 
Lo que hace este código es que encuentra algunas versiones que están instaladas en el servidor y cuales son los localismos válidos para poder usarlos en el segundo parámetro de setlocale y así dejar de sufrir.
Este código pégalo en un archivo nuevo de php en tu servidor y córrelo desde tu explorador y te mostrará los valores deseados al menos de estos idiomas: Dutch (Holandes), German (Aleman), English (Ingles) y Spanish (Español), si deseas más idiomas hay que saber un poco de desarrollo de php y editar el script arriba preformateado. 
 

Centro de Formación

Calidad en la entrega,
Rentabilidad en la inversión.

Contactar Ahora