Previous Next

Using Zend_Locale

Zend_Locale also provides localized information about locales for each locale, including localized names for other locales, days of the week, month names, etc.

Copying, Cloning, and Serializing Locale Objects

Use » object cloning to duplicate a locale object exactly and efficiently. Most locale-aware methods also accept string representations of locales, such as the result of $locale->toString().

Ejemplo #1 clone

$locale = new Zend_Locale('ar');

// Save the $locale object as a serialization
$serializedLocale = $locale->serialize();
// re-create the original object
$localeObject = unserialize($serializedLocale);

// Obtain a string identification of the locale
$stringLocale = $locale->toString();

// Make a cloned copy of the $local object
$copiedLocale = clone $locale;

print "copied: ", $copiedLocale->toString();

// PHP automatically calls toString() via __toString()
print "copied: ", $copiedLocale;

Equality

Zend_Locale also provides a convenience function to compare two locales. All locale-aware classes should provide a similar equality check.

Ejemplo #2 Check for equal locales

$locale = new Zend_Locale();
$mylocale = new Zend_Locale('en_US');

// Check if locales are equal
if ($locale->equals($mylocale)) {
    print "Locales are equal";
}

Default locales

The method getDefault() returns an array of relevant locales using information from the user's web browser (if available), information from the environment of the host server, and Zend Framework settings. As with the constructor for Zend_Locale, the first parameter selects a preference of which information to consider (BROWSER, ENVIRONMENT, or FRAMEWORK first. The second parameter toggles between returning all matching locales or only the first or best match. Locale-aware components normally use only the first locale. A quality rating is included, when available.

Ejemplo #3 Get default locales

$locale = new Zend_Locale();

// Return all default locales
$found = $locale->getDefault();
print_r($found);

// Return only browser locales
$found2 = $locale->getDefault(Zend_Locale::BROWSER,TRUE);
print_r($found2);

To obtain only the default locales relevant to the BROWSER, ENVIRONMENT, or FRAMEWORK, use the corresponding method:

  • getEnvironment()

  • getBrowser()

  • getLocale()

Set a new locale

A new locale can be set with the function setLocale(). This function takes a locale string as parameter. If no locale is given, a locale is automatically selected.

Ejemplo #4 setLocale

$locale = new Zend_Locale();

// Actual locale
print $locale->toString();

// new locale
$locale->setLocale('aa_DJ');
print $locale->toString();

Getting the language and region

Use getLanguage() to obtain a string containing the two character language code from the string locale identifier. Use getRegion() to obtain a string containing the two character region code from the string locale identifier.

Ejemplo #5 getLanguage and getRegion

$locale = new Zend_Locale();

// if locale is 'de_AT' then 'de' will be returned as language
print $locale->getLanguage();

// if locale is 'de_AT' then 'AT' will be returned as region
print $locale->getRegion();

Get the locale by giving a territory

When you only have the territory or country then it's also possible to get a locale from that information. You can manually search if there is a locale for this territory by using getLocaleToTerritory(). This method returns a locale for the given territory or NULL when there was has no locale been found.

Ejemplo #6 getLocaleToTerritory

$locale = Zend_Locale::getLocaleToTerritory('US');
// returns 'en_US'

Nota: Uppercase territories

When you know that you are using a territory, then you should uppercase it. Otherwise you could get an in your eyes false locale in return when you use other methods. For example: When you give "om" then getLocaleToTerritory() returns you "ar_OM" as it knows that you mean a territory. But all other methods will return "om", as it's also a language.

So when you know that the given string is a territory, eighter use getLocaleToTerritory() yourself before creating a locale, or uppercase the input.

Obtaining localized strings

getTranslationList() gives you access to localized information of several types. These information are useful if you want to display localized data to a customer without the need of translating it. They are already available for your usage.

The requested list of information is always returned as named array. If you want to give more than one value to a explicit type where you wish to receive values from, you have to give an array instead of multiple values.

Ejemplo #7 getTranslationList

$list = Zend_Locale::getTranslationList('language', 'de_AT');

print_r ($list);
// example key -> value pairs...
// [de] -> Deutsch
// [en] -> Englisch

// use one of the returned key as value for the getTranslation() method
// of another language
print Zend_Locale::getTranslation('de', 'language', 'zh');
// returns the translation for the language 'de' in chinese

You can receive this information for all languages. But not all information is completely available for all languages. Some of these types are also available through an own function for simplicity. See this list for detailed information.

Details for getTranslationList($type = null, $locale = null, $value = null)
Type Description
Language Returns a localized list of all languages. The language part of the locale is returned as key and the translation as value
Script Returns a localized list of all scripts. The script is returned as key and the translation as value
Territory Returns a localized list of all territories. This contains countries, continents and territories. To get only territories and continents use '1' as value. To get only countries use '2' as value. The country part of the locale is used as key where applicable. In the other case the official ISO code for this territory is used. The translated territory is returned as value. When you omit the value you will get a list with both.
Variant Returns a localized list of known variants of scripts. The variant is returned as key and the translation as value
Key Returns a localized list of known keys. This keys are generic values used in translation. These are normally calendar, collation and currency. The key is returned as array key and the translation as value
Type Returns a localized list of known types of keys. These are variants of types of calendar representations and types of collations. When you use 'collation' as value you will get all types of collations returned. When you use 'calendar' as value you will get all types of calendars returned. When you omit the value you will get a list all both returned. The type is used as key and the translation as value
Layout Returns a list of rules which describes how to format special text parts
Characters Returns a list of allowed characters within this locale
Delimiters Returns a list of allowed quoting characters for this locale
Measurement Returns a list of known measurement values. This list is depreciated
Months Returns a list of all month representations within this locale. There are several different representations which are all returned as sub array. If you omit the value you will get a list of all months from the 'gregorian' calendar returned. You can give any known calendar as value to get a list of months from this calendar returned. Use Zend_Date for simplicity
Month Returns a localized list of all month names for this locale. If you omit the value you will get the normally used gregorian full name of the months where each month number is used as key and the translated month is returned as value. You can get the months for different calendars and formats if you give an array as value. The first array entry has to be the calendar, the second the used context and the third the width to return. Use Zend_Date for simplicity
Days Returns a list of all day representations within this locale. There are several different representations which are all returned as sub array. If you omit the value you will get a list of all days from the 'gregorian' calendar returned. You can give any known calendar as value to get a list of days from this calendar returned. Use Zend_Date for simplicity
Day Returns a localized list of all day names for this locale. If you omit the value you will get the normally used gregorian full name of the days where the english day abbreviation is used as key and the translated day is returned as value. You can get the days for different calendars and formats if you give an array as value. The first array entry has to be the calendar, the second the used context and the third the width to return. Use Zend_Date for simplicity
Week Returns a list of values used for proper week calculations within a locale. Use Zend_Date for simplicity
Quarters Returns a list of all quarter representations within this locale. There are several different representations which are all returned as sub array. If you omit the value you will get a list of all quarters from the 'gregorian' calendar returned. You can give any known calendar as value to get a list of quarters from this calendar returned
Quarter Returns a localized list of all quarter names for this locale. If you omit the value you will get the normally used gregorian full name of the quarters where each quarter number is used as key and the translated quarter is returned as value. You can get the quarters for different calendars and formats if you give an array as value. The first array entry has to be the calendar, the second the used context and the third the width to return
Eras Returns a list of all era representations within this locale. If you omit the value you will get a list of all eras from the 'gregorian' calendar returned. You can give any known calendar as value to get a list of eras from this calendar returned
Era Returns a localized list of all era names for this locale. If you omit the value you will get the normally used gregorian full name of the eras where each era number is used as key and the translated era is returned as value. You can get the eras for different calendars and formats if you give an array as value. The first array entry has to be the calendar and the second the width to return
Date Returns a localized list of all date formats for this locale. The name of the dateformat is used as key and the format itself as value.If you omit the value you will get the date formats for the gregorian calendar returned. You can get the date formats for different calendars if you give the wished calendar as string. Use Zend_Date for simplicity
Time Returns a localized list of all time formats for this locale. The name of the timeformat is used as key and the format itself as value. If you omit the value you will get the time formats for the gregorian calendar returned. You can get the time formats for different calendars if you give the wished calendar as string. Use Zend_Date for simplicity
DateTime Returns a localized list of all known date-time formats for this locale. The name of the date-time format is used as key and the format itself as value. If you omit the value you will get the date-time formats for the gregorian calendar returned. You can get the date-time formats for different calendars if you give the wished calendar as string. Use Zend_Date for simplicity
DateItem Returns a list of default formats for given date or time items
DateInterval Returns a list of date or time formats which are used when you want to display intervals. The list is a multidimentional array where the first dimension is the interval format, and the second dimension is the token with the greatest difference.
Field Returns a localized list of date fields which can be used to display calendars or date strings like 'month' or 'year' in a wished language. If you omit the value you will get this list for the gregorian calendar returned. You can get the list for different calendars if you give the wished calendar as string
Relative Returns a localized list of relative dates which can be used to display textual relative dates like 'yesterday' or 'tomorrow' in a wished language. If you omit the value you will get this list for the gregorian calendar returned. You can get the list for different calendars if you give the wished calendar as string
Symbols Returns a localized list of characters used for number representations
NameToCurrency Returns a localized list of names for currencies. The currency is used as key and the translated name as value. Use Zend_Currency for simplicity
CurrencyToName Returns a list of currencies for localized names. The translated name is used as key and the currency as value. Use Zend_Currency for simplicity
CurrencySymbol Returns a list of known localized currency symbols for currencies. The currency is used as key and the symbol as value. Use Zend_Currency for simplicity
Question Returns a list of localized strings for acceptance ('yes') and negation ('no'). Use Zend_Locale's getQuestion method for simplicity
CurrencyFraction Returns a list of fractions for currency values. The currency is used as key and the fraction as integer value. Use Zend_Currency for simplicity
CurrencyRounding Returns a list of how to round which currency. The currency is used as key and the rounding as integer value. Use Zend_Currency for simplicity
CurrencyToRegion Returns a list of currencies which are known to be used within a region. The ISO3166 value ('region') is used as array key and the ISO4217 value ('currency') as array value. Use Zend_Currency for simplicity
RegionToCurrency Returns a list of regions where a currency is used . The ISO4217 value ('currency') is used as array key and the ISO3166 value ('region') as array value. When a currency is used in several regions these regions are separated with a whitespace. Use Zend_Currency for simplicity
RegionToTerritory Returns a list of territories with the countries or sub territories which are included within that territory. The ISO territory code ('territory') is used as array key and the ISO3166 value ('region') as array value. When a territory contains several regions these regions are separated with a whitespace
TerritoryToRegion Returns a list of regions and the territories where these regions are located. The ISO3166 code ('region') is used as array key and the ISO territory code ('territory') as array value. When a region is located in several territories these territories are separated with a whitespace
ScriptToLanguage Returns a list of scripts which are used within a language. The language code is used as array key and the script code as array value. When a language contains several scripts these scripts are separated with a whitespace
LanguageToScript Returns a list of languages which are using a script. The script code is used as array key and the language code as array value. When a script is used in several languages these languages are separated with a whitespace
TerritoryToLanguage Returns a list of languages and the countries where they are spoken. The language is used as array key and the country code as array value. When a language is used in several countries these countries are separated with a whitespace
LanguageToTerritory Returns a list of countries and the languages which are spoken within them. The country code is used as array key and the language code as array value. When several languages are spoken within a territory then these languages are separated with a whitespace
TimezoneToWindows Returns a list of windows timezones and the related ISO timezone. The windows timezone is used as array key and the ISO timezone as array value
WindowsToTimezone Returns a list of ISO timezones and the related windows timezone. The ISO timezone is used as array key and the windows timezone as array value
TerritoryToTimezone Returns a list of regions or territories and the related ISO timezone. The ISO timezone is used as array key and the territory code as array value
TimezoneToTerritory Returns a list of timezones and the related region or territory code. The region or territory code is used as array key and the ISO timezone as array value
CityToTimezone Returns a localized list of cities which can be used as translation for a related timezone. Not for all timezones is a translation available, but for a user is the real city written in his languages more accurate than the ISO name of this timezone. The ISO timezone is used as array key and the translated city as array value
TimezoneToCity Returns a list of timezones for localized city names. The localized city is used as array key and the ISO timezone name as array value
PhoneToTerritory Returns a list of phone codes which are known to be used within a territory. The territory (region) is used as array key and the telephone code as array value
TerritoryToPhone Returns a list of territories where a phone is used . The phone code is used as array key and the territory (region) as array value. When a phone code is used in several territories these territories are separated with a whitespace
NumericToTerritory Returns a list of 3 digit number codes for territories. The territory (region) is used as array key and the 3 digit number code as array value
TerritoryToNumeric Returns a list of territories with their 3 digit number code. The 3 digit number code is used as array key and the territory (region) as array value
Alpha3ToTerritory Returns a list of 3 sign character codes for territories. The territory (region) is used as array key and the 3 sign character code as array value
TerritoryToAlpha3 Returns a list of territories with their 3 sign character code. The 3 sign character code is used as array key and the territory (region) as array value
PostalToTerritory Returns a list of territories with a regex for postal codes which are included within that territory. The ISO territory code ('territory') is used as array key and the regex as array value.
NumberingSystem Returns a list of scripts with the notation for digits used within the script
FallbackToChar Returns a list of replacement characters for often used unicode characters. This can be used to replace "©" with "(C)" for example
CharToFallback Returns a list of unicode characters for often used replacement characters. This can be used to replace "(C)" with "©" for example
LocaleUpgrade Returns a list of locale dependencies which can be used to upgrade a language to a full qualified locale
Unit Returns a list of localized calendar units. This can be used to translate the strings "day", "month" and so on automatically

If you are in need of a single translated value, you can use the getTranslation() method. It always returns a string but it accepts some different types than the getTranslationList() method. Also value is the same as before with one difference. You have to give the detail you want to get returned as additional value.

Nota:

Because you have almost always give a value as detail this parameter has to be given as first parameter. This differs from the getTranslationList() method.

See the following table for detailed information:

Details for getTranslation($value = null, $type = null, $locale = null)
Type Description
Language Returns a translation for a language. To select the wished translation you must give the language code as value
Script Returns a translation for a script. To select the wished translation you must give the script code as value
Territory or Country Returns a translation for a territory. This can be countries, continents and territories. To select the wished variant you must give the territory code as value
Variant Returns a translation for a script variant. To select the wished variant you must give the variant code as value
Key Returns translation for a known keys. This keys are generic values used in translation. These are normally calendar, collation and currency. To select the wished key you must give the key code as value
DefaultCalendar Returns the default calendar for the given locale. For most locales this will be 'gregorian'. Use Zend_Date for simplicity
MonthContext Returns the default context for months which is used within the given calendar. If you omit the value the 'gregorian' calendar will be used. Use Zend_Date for simplicity
DefaultMonth Returns the default format for months which is used within the given calendar. If you omit the value the 'gregorian' calendar will be used. Use Zend_Date for simplicity
Month Returns a translation for a month. You have to give the number of the month as integer value. It has to be between 1 and 12. If you want to receive data for other calendars, contexts or formats, then you must give an array instead of an integer with the expected values. The array has to look like this: array( 'calendar', 'context', 'format', 'month number'). If you give only an integer then the default values are the 'gregorian' calendar, the context 'format' and the format 'wide'. Use Zend_Date for simplicity
DayContext Returns the default context for ´days which is used within the given calendar. If you omit the value the 'gregorian' calendar will be used. Use Zend_Date for simplicity
DefaultDay Returns the default format for days which is used within the given calendar. If you omit the value the 'gregorian' calendar will be used. Use Zend_Date for simplicity
Day Returns a translation for a day. You have to give the english abbreviation of the day as string value ('sun', 'mon', etc.). If you want to receive data for other calendars, contexts or format, then you must give an array instead of an integer with the expected values. The array has to look like this: array('calendar', 'context', 'format', 'day abbreviation'). If you give only an string then the default values are the 'gregorian' calendar, the context 'format' and the format 'wide'. Use Zend_Date for simplicity
Quarter Returns a translation for a quarter. You have to give the number of the quarter as integer and it has to be between 1 and 4. If you want to receive data for other calendars, contexts or formats, then you must give an array instead of an integer with the expected values. The array has to look like this: array('calendar', 'context', 'format', 'quarter number'). If you give only an string then the default values are the 'gregorian' calendar, the context 'format' and the format 'wide'
Am Returns translation for 'AM' in the expected locale. If you want to receive data for other calendars provide a string with the expected calendar. If you omit the value then the 'gregorian' calendar will be used. Use Zend_Date for simplicity
Pm Returns translation for 'PM' in the expected locale. If you want to receive data for other calendars provide a string with the expected calendar. If you omit the value then the 'gregorian' calendar will be used. Use Zend_Date for simplicity
Era Returns a translation for an era within a locale. You have to give the era number as string or integer. If you want to receive data for other calendars or formats, then you must give an array instead of the era number with the expected values. The array has to look like this: array('calendar', 'format', 'era number'). If you give only a string then the default values are the 'gregorian' calendar and the 'abbr' format
DefaultDate Returns the default date format which is used within the given calendar. If you omit the value the 'gregorian' calendar will be used. Use Zend_Date for simplicity
Date Returns the date format for a given calendar or format within a locale. If you omit the value then the 'gregorian' calendar will be used with the 'medium' format. If you give a string then the 'gregorian' calendar will be used with the given format. Or you can also give an array which will have to look like this: array('calendar', 'format'). Use Zend_Date for simplicity
DefaultTime Returns the default time format which is used within the given calendar. If you omit the value the 'gregorian' calendar will be used. Use Zend_Date for simplicity
Time Returns the time format for a given calendar or format within a locale. If you omit the value then the 'gregorian' calendar will be used with the 'medium' format. If you give a string then the 'gregorian' calendar will be used with the given format. Or you can also give an array which will have to look like this: array('calendar', 'format'). Use Zend_Date for simplicity
DateTime Returns the datetime format for the given locale which indicates how to display date with times in the same string within the given calendar. If you omit the value the 'gregorian' calendar will be used. Use Zend_Date for simplicity
DateItem Returns the default format for a given date or time item
DateInterval Returns the interval format for a given date or time format. The first value is the calendar format, normally 'gregorian'. The second value is the interval format and the third value the token with the greatest difference. For example: array('gregorian', 'yMMMM', 'y') returns the interval format for the date format 'yMMMM' where 'y' has the greatest difference.
Field Returns a translated date field which can be used to display calendars or date strings like 'month' or 'year' in a wished language. You must give the field which has to be returned as string. In this case the 'gregorian' calendar will be used. You can get the field for other calendar formats if you give an array which has to look like this: array('calendar', 'date field')
Relative Returns a translated date which is relative to today which can include date strings like 'yesterday' or 'tomorrow' in a wished language. You have to give the number of days relative to tomorrow to receive the expected string. Yesterday would be '-1', tomorrow '1' and so on. This will use the 'gregorian' calendar. if you want to get relative dates for other calendars you will have to give an array which has to look like this: array('calendar', 'relative days'). Use Zend_Date for simplicity
DecimalNumber Returns the format for decimal numbers within a given locale. Use Zend_Locale_Format for simplicity
ScientificNumber Returns the format for scientific numbers within a given locale
PercentNumber Returns the format for percentage numbers within a given locale
CurrencyNumber Returns the format for displaying currency numbers within a given locale. Use Zend_Currency for simplicity
NameToCurrency Returns the translated name for a given currency. The currency has to be given in ISO format which is for example 'EUR' for the currency 'euro'. Use Zend_Currency for simplicity
CurrencyToName Returns a currency for a given localized name. Use Zend_Currency for simplicity
CurrencySymbol Returns the used symbol for a currency within a given locale. Not for all currencies exists a symbol. Use Zend_Currency for simplicity
Question Returns a localized string for acceptance ('yes') and negation ('no'). You have to give either 'yes' or 'no' as value to receive the expected string. Use Zend_Locale's getQuestion method for simplicity
CurrencyFraction Returns the fraction to use for a given currency. You must give the currency as ISO value. Use Zend_Currency for simplicity
CurrencyRounding Returns how to round a given currency. You must give the currency as ISO value. If you omit the currency then the 'DEFAULT' rounding will be returned. Use Zend_Currency for simplicity
CurrencyToRegion Returns the currency for a given region. The region code has to be given as ISO3166 string for example 'AT' for austria. Use Zend_Currency for simplicity
RegionToCurrency Returns the regions where a currency is used. The currency has to be given as ISO4217 code for example 'EUR' for euro. When a currency is used in multiple regions, these regions are separated with a whitespace character. Use Zend_Currency for simplicity
RegionToTerritory Returns the regions for a given territory. The territory has to be given as ISO4217 string for example '001' for world. The regions within this territory are separated with a whitespace character
TerritoryToRegion Returns the territories where a given region is located. The region has to be given in ISO3166 string for example 'AT' for austria. When a region is located in multiple territories then these territories are separated with a whitespace character
ScriptToLanguage Returns the scripts which are used within a given language. The language has to be given as ISO language code for example 'en' for english. When multiple scripts are used within a language then these scripts are separated with a whitespace character
LanguageToScript Returns the languages which are used within a given script. The script has to be given as ISO script code for example 'Latn' for latin. When a script is used in multiple languages then these languages are separated with a whitespace character
TerritoryToLanguage Returns the territory where a given language is used. The language has to be given as ISO language code for example 'en' for english. When the given language is spoken within multiple territories then these territories are separated with a whitespace character
LanguageToTerritory Returns the language which is spoken within a given territory. The territory has to be given as ISO3166 code for example 'IT' for italia. When multiple languages are spoken within the given territory then these languages are separated with a whitespace character
TimezoneToWindows Returns a ISO timezone for a given windows timezone
WindowsToTimezone Returns a windows timezone for a given ISO timezone
TerritoryToTimezone Returns the territory for a given ISO timezone
TimezoneToTerritory Returns the ISO timezone for a given territory
CityToTimezone Returns the localized city for a given ISO timezone. Not for all timezones does a city translation exist
TimezoneToCity Returns the ISO timezone for a given localized city name. Not for all cities does a timezone exist
PhoneToTerritory Returns the telephone code for a given territory (region). The territory code has to be given as ISO3166 string for example 'AT' for austria
TerritoryToPhone Returns the territory (region) where a telephone code is used. The telephone code has to be given as plain integer code for example '43' for +43. When a telephone code is used in multiple territories (regions), these territories are separated with a whitespace character
NumericToTerritory Returns the 3 digit number code for a given territory (region). The territory code has to be given as ISO3166 string for example 'AT' for austria
TerritoryToNumeric Returns the territory (region) for a 3 digit number code. The 3 digit number code has to be given as plain integer code for example '43'
Alpha3ToTerritory Returns the 3 sign character code for a given territory (region). The territory code has to be given as ISO3166 string for example 'AT' for austria
TerritoryToAlpha3 Returns the territory (region) for a 3 sign character code
PostalToTerritory Returns the a regex for postal codes for a given territory. The territory has to be given as ISO4217 string for example '001' for world
NumberingSystem Returns a scripts with the notation for digits used within this script
FallbackToChar Returns a replacement character for a often used unicode character. This can be used to replace "©" with "(C)" for example
CharToFallback Returns a unicode character for a often used replacement character. This can be used to replace "(C)" with "©" for example
LocaleUpgrade Returns a locale dependencies for a given language which can be used to upgrade this language to a full qualified locale
Unit Returns a localized calendar unit. This can be used to translate the strings "day", "month" and so on automatically. The first parameter has to be the type, and the second parameter has to be the count

Nota:

With Zend Framework 1.5 several old types have been renamed. This has to be done because of several new types, some misspelling and to increase the usability. See this table for a list of old to new types:

Differences between Zend Framework 1.0 and 1.5
Old type New type
Country Territory (with value '2')
Calendar Type (with value 'calendar')
Month_Short Month (with array('gregorian', 'format', 'abbreviated')
Month_Narrow Month (with array('gregorian', 'stand-alone', 'narrow')
Month_Complete Months
Day_Short Day (with array('gregorian', 'format', 'abbreviated')
Day_Narrow Day (with array('gregorian', 'stand-alone', 'narrow')
DateFormat Date
TimeFormat Time
Timezones CityToTimezone
Currency NameToCurrency
Currency_Sign CurrencySymbol
Currency_Detail CurrencyToRegion
Territory_Detail TerritoryToRegion
Language_Detail LanguageToTerritory

The example below demonstrates how to obtain the names of things in different languages.

Ejemplo #8 getTranslationList

// prints the names of all countries in German language
print_r(Zend_Locale::getTranslationList('country', 'de'));

The next example shows how to find the name of a language in another language, when the two letter iso country code is not known.

Ejemplo #9 Converting country name in one language to another

$code2name = Zend_Locale::getLanguageTranslationList('en_US');
$name2code = array_flip($code2name);
$frenchCode = $name2code['French'];
echo Zend_Locale::getLanguageTranslation($frenchCode, 'de_AT');
// output is the German name of the French language

To generate a list of all languages known by Zend_Locale, with each language name shown in its own language, try the example below in a web page. Similarly, getCountryTranslationList() and getCountryTranslation() could be used to create a table mapping your native language names for regions to the names of the regions shown in another language. Use a try .. catch block to handle exceptions that occur when using a locale that does not exist. Not all languages are also locales. In the example, below exceptions are ignored to prevent early termination.

Ejemplo #10 All Languages written in their native language

$list = Zend_Locale::getLanguageTranslationList('auto');

foreach($list as $language => $content) {
    try {
        $output = Zend_Locale::getLanguageTranslation($language, $language);
        if (is_string($output)) {
            print "\n
[".$language."] ".$output; } } catch (Exception $e) { continue; } }

Obtaining translations for "yes" and "no"

Frequently, programs need to solicit a "yes" or "no" response from the user. Use getQuestion() to obtain an array containing the correct word(s) or regex strings to use for prompting the user in a particular $locale (defaults to the current object's locale). The returned array will contain the following information :

  • yes and no: A generic string representation for yes and no responses. This will contain the first and most generic response from yesarray and noarray.

    yesarray and noarray: An array with all known yes and no responses. Several languages have more than just two responses. In general this is the full string and its abbreviation.

    yesexpr and noexpr: A generated regex which allows you to handle user response, and search for yes or no.

All of this information are of course localized and depend on the set locale. See the following example for the information you can receive:

Ejemplo #11 getQuestion()

$locale = new Zend_Locale();
// Question strings
print_r($locale->getQuestion('de'));

- - - Output - - -

Array
(
    [yes] => ja
    [no] => nein
    [yesarray] => Array
        (
            [0] => ja
            [1] => j
        )

    [noarray] => Array
        (
            [0] => nein
            [1] => n
        )

    [yesexpr] => ^([jJ][aA]?)|([jJ]?)
    [noexpr] => ^([nN]([eE][iI][nN])?)|([nN]?)
)

Nota:

Until 1.0.3 yesabbr from the underlaying locale data was also available. Since 1.5 this information is no longer standalone available, but you will find the information from it within yesarray.

Get a list of all known locales

Sometimes you will want to get a list of all known locales. This can be used for several tasks like the creation of a selectbox. For this purpose you can use the static getLocaleList() method which will return a list of all known locales.

Ejemplo #12 getLocaleList()

$localelist = Zend_Locale::getLocaleList();

Nota:

Note that the locales are returned as key of the array you will receive. The value is always a boolean TRUE.

Detecting locales

When you want to detect if a given input, regardless of its source, is a locale you should use the static isLocale() method. The first parameter of this method is the string which you want to check.

Ejemplo #13 Simple locale detection

$input = 'to_RU';
if (Zend_Locale::isLocale($input)) {
    print "'{$input}' is a locale";
} else {
    print "Sorry... the given input is no locale";
}

As you can see, the output of this method is always a boolean. There is only one reason you could get an exception when calling this method. When your system does not provide any locale and Zend Framework is not able to detect it automatically. Normally this shows that there is a problem with your OS in combination with PHP's setlocale().

You should also note that any given locale string will automatically be degraded if the region part does not exist for this locale. In our previous example the language 'to' does not exist in the region 'RU', but you will still get TRUE returned as Zend_Locale can work with the given input.

Still it's sometimes useful to prevent this automatic degrading, and this is where the second parameter of isLocale() comes in place. The strict parameter defaults to FALSE and can be used to prevent degrading when set to TRUE.

Ejemplo #14 Strict locale detection

$input = 'to_RU';
if (Zend_Locale::isLocale($input, true)) {
    print "'{$input}' is a locale";
} else {
    print "Sorry... the given input is no locale";
}

Now that you are able to detect if a given string is a locale you could add locale aware behaviour to your own classes. But you will soon detect that this always leads to the same 15 lines of code. Something like the following example:

Ejemplo #15 Implement locale aware behaviour

if ($locale === null) {
    $locale = new Zend_Locale();
}

if (!Zend_Locale::isLocale($locale, true, false)) {
    if (!Zend_Locale::isLocale($locale, false, false)) {
        throw new Zend_Locale_Exception(
            "The locale '$locale' is no known locale");
    }

    $locale = new Zend_Locale($locale);
}

if ($locale instanceof Zend_Locale) {
    $locale = $locale->toString();
}

With Zend Framework 1.8 we added a static findLocale() method which returns a locale string which you can work with. It processes the following tasks:

  • Detects if a given string is a locale

  • Degrades the locale if it does not exist in the given region

  • Upgrades the locale when it is detected as region without language

  • Returns a previous set application wide locale if no input is given

  • Detects the locale from browser when the previous detections failed

  • Detects the locale from environment when the previous detections failed

  • Detects the locale from framework when the previous detections failed

  • Returns always a string which represents the found locale.

The following example shows how these checks and the above code can be simplified with one single call:

Ejemplo #16 Locale aware behaviour as with Zend Framework 1.8

$locale = Zend_Locale::findLocale($inputstring);
Previous Next
Introducción a Zend Framework
Descripción general
Instalación
Aprendiendo Zend Framework
Inicio Rápido con Zend Framework
Introducción a MVC & ZF
Create Your Project
Create A Layout
Create a Model and Database Table
Create A Form
¡Felicitaciones!
Autocarga o Carga automática en Zend Framework
Introduction
Goals and Design
Basic Autoloader Usage
Resource Autoloading
Conclusion
Plugins en Zend Framework
Introduction
Using Plugins
Conclusion
Primeros pasos con Zend_Layout
Introduction
Using Zend_Layout
Zend_Layout: Conclusions
Introducción a Zend_View Placeholders
Introduction
Basic Placeholder Usage
Standard Placeholders
View Placeholders: Conclusion
Comprensión y uso de Zend Form Decorators
Introduction
Decorator Basics
Layering Decorators
Rendering Individual Decorators
Creating and Rendering Composite Elements
Conclusión
Primeros pasos con Zend_Session, Zend_Auth, and Zend_Acl
Building Multi-User Applications With Zend Framework
Managing User Sessions In ZF
Authenticating Users in Zend Framework
Building an Authorization System in Zend Framework
Primeros pasos con Zend_Search_Lucene
Zend_Search_Lucene Introduction
Lucene Index Structure
Index Opening and Creation
Indexing
Searching
Supported queries
Search result pagination
Primeros pasos con Zend_Paginator
Introduction
Simple Examples
Pagination Control and ScrollingStyles
Putting it all Together
Referencia de Zend Framework
Zend_Acl
Introducción
Perfeccionamiento de los controles de acceso
Uso Avanzado
Zend_Amf
Introducción
Zend_Amf_Server
Zend_Application
Introducción
Inicio rápido con Zend_Application
Teoría de Operación
Ejemplos
Funcionalidad Básica
Plugins de Recursos Disponibles
Zend_Auth
Introducción
Tabla de base de datos de autenticación
Autenticación "Digest"
Adaptador de Autenticación HTTP
LDAP Authentication
Autenticación con Open ID
Zend_Barcode
Introduction
Barcode creation using Zend_Barcode class
Zend_Barcode Objects
Zend_Barcode Renderers
Zend_Cache
Introducción
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
The Cache Manager
Zend_Captcha
Introducción
Captcha Operation
CAPTCHA Adapters
SimpleCloud API: Zend_Cloud
Document Service Introduction
Queue Service Introduction
StorageService Introduction
Zend_CodeGenerator
Introducción
Ejemplos de Zend_CodeGenerator
Referencias de Zend_CodeGenerator
Zend_Config
Introducción
Aspectos Teóricos
Zend_Config_Ini
Zend_Config_Json
Zend_Config_Xml
Zend_Config_Yaml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Inicio rápido a Zend_Controller
Conceptos Básicos de Zend_Controller
El Front Controller
La solicitud del Objeto
El Router Standard
El Despachador
Controladores de Acción
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
Excepciones MVC
Zend_Currency
Introduction to Zend_Currency
Using Zend_Currency
Options for currencies
What makes a currency?
Where is the currency?
How does the currency look like?
How much is my currency?
Calculating with currencies
Exchanging currencies
Additional informations on Zend_Currency
Zend_Date
Introducción
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Db_Table_Definition
Zend_Debug
Mostrar información de variables(Dumping Variables)
Zend_Dojo
Introducción
Zend_Dojo_Data: Envolturas de dojo.data
Ayudantes de Dojo View
Elementos y Decoradores de Dojo Form
Zend_Dojo build layer support
Zend_Dom
Introducción
Zend_Dom_Query
Zend_Exception
Uso de Excepciones
Basic usage
Previous Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_Feed_Reader
Zend_Feed_Writer
Zend_Feed_Pubsubhubbub
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Zend_Filter
Introducción
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Inicio rápido a Zend_Form
Creando elementos de formulario usando Zend_Form_Element
Creando formularios usando Zend_Form
Creando un personalizado marcado de formulario usando Zend_Form_Decorator
Elementos Enviados en el Formulario Estandard de Zend Framework
Decoradores de Formulario (Form Decorartors) estándar contenidos en Zend Framework
Internacionalización de Zend_Form
Uso avanzado de Zend_Form
Zend_Gdata
Introduction
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_Http_UserAgent
The UserAgent Device Interface
The UserAgent Features Adapter
The WURFL UserAgent Features Adapter
The DeviceAtlas UserAgent Features Adapter
The TeraWurfl UserAgent Features Adapter
The UserAgent Storage Interface
The Session UserAgent Storage Adapter
Zend_InfoCard
Introduction
Zend_Json
Introducción
Uso Básico
Uso Avanzado de Zend_Json
Conversión de XML a JSON
Zend_Json_Server - servidor JSON-RPC
Zend_Layout
Introducción
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
API overview
Usage Scenarios
Tools
Object oriented access to the LDAP tree using Zend_Ldap_Node
Getting information from the LDAP server
Serializing LDAP data to and from LDIF
Zend_Loader
Cargando archivos y clases dinámicamente
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Zend_Log
Overview
Writers
Formatters
Filters
Using the Factory to Create a Log
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Markup
Introduction
Getting Started With Zend_Markup
Zend_Markup Parsers
Zend_Markup Renderers
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Zend_Oauth
Introduction to OAuth
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introducción
Creando y Cargando Documentos PDF
Guardar Cambios a Documentos PDF
Trabajando con Páginas
Dibujo
Interactive Features
Información del Documento y Metadatos
Ejemplo de Uso del módulo Zend_Pdf
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
Introduction
Example usage
Framework
Adapters
Customizing Zend_Queue
Stomp
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Serializer
Introduction
Zend_Serializer_Adapter
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Storage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Amazon_Sqs
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_DeveloperGarden
Zend_Service_Ebay
Zend_Service_Ebay_Finding
Zend_Service_Flickr
Zend_Service_LiveDocx
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_ShortUrl
Zend_Service_Simpy
Zend_Service_SlideShare
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_WindowsAzure
Zend_Service_WindowsAzure_Storage_Blob
Zend_Service_WindowsAzure_Diagnostics_Manager
Zend_Service_WindowsAzure_Storage_Queue
Zend_Service_WindowsAzure_Storage_Table
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introducción
Zend_Test_PHPUnit
Zend_Test_PHPUnit_Db
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool
Using Zend_Tool On The Command Line
Extending Zend_Tool
Zend_Tool_Framework
Introduction
Usando la herramienta CLI
Architecture
Creando Proveedores para usar con Zend_Tool_Framework
Shipped System Providers
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
Introduction
Create A Project
Zend_Tool Project Providers
Zend_Tool_Project Internos
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Creating source files
Additional features for translation
Plural notations for Translation
Zend_Uri
Zend_Uri
Zend_Validate
Introducción
Clases de Validación Estándar
Cadenas de Validadores
Escribiendo Validadores
Validation Messages
Zend_Version
Obteniendo la versión de Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introducción
Zend_XmlRpc_Client
Zend_XmlRpc_Server
ZendX_Console_Process_Unix
ZendX_Console_Process_Unix
ZendX_JQuery
Introduction
ZendX_JQuery View Helpers
ZendX_JQuery Form Elements and Decorators
Requisitos de Zend Framework
Versión de PHP
Extensiones de PHP
Componentes de Zend Framework
Dependencias de Zend Framework
Notas de Migración de Zend Framework
Zend Framework 1.10
Zend Framework 1.9
Zend Framework 1.8
Zend Framework 1.7
Zend Framework 1.6
Zend Framework 1.5
Zend Framework 1.0
Zend Framework 0.9
Zend Framework 0.8
Zend Framework 0.6
Estándares de codificación de Zend Framework para PHP
Introducción
Formato de archivos PHP
Convenciones de Nombres
Estilo de código
Zend Framework Documentation Standard
Overview
Documentation File Formatting
Recommendations
Recommended Project Structure for Zend Framework MVC Applications
Overview
Recommended Project Directory Structure
Module Structure
Rewrite Configuration Guide
Guía de Rendimiento de Zend Framework
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information