archlinux модуль php gettext

Archlinux модуль php gettext

PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.

Contents

Installation

Running

While PHP can be run standalone, it is typically used with web servers. That requires installing additional packages and editing configuration files. For common setups, see the following:

To run PHP scripts as plain CGI, you need the php-cgi package.

Configuration

Extensions

A number of commonly used PHP extensions can also be found in the official repositories:

For php-gd uncomment the line in /etc/php/php.ini :

Imagemagick

Install the imagemagick package and install one of the listed PHP extension library.

Make sure the php-pear AUR package has been installed:

Create a /etc/php/conf.d/imagick.ini and enable the extension:

Multithreading

PCNTL

PCNTL allows you to create process directly into the server side machine. While this may seen as something you would want, it also gives PHP the power to mess things up really badly. So it is a PHP extension that cannot be loaded like other more convenient extension. This is because of the great power it gives to PHP. To enable it PCNTL has to be compiled into PHP.

The php package on Arch Linux is currently built with «—enable-pcntl», so that it should be available by default.

MySQL/MariaDB

Install and configure MySQL/MariaDB as described in MariaDB.

Uncomment the following lines in /etc/php/php.ini :

You can add minor privileged MySQL users for your web scripts. You might also want to edit /etc/my.cnf.d/server.cnf and add in mysqld section skip-networking line so the MySQL server is only accessible by the localhost, as per MariaDB#Enable access locally only via Unix sockets. You have to restart MySQL for changes to take effect.

Redis

PostgreSQL

Install and configure PostgreSQL, then install the php-pgsql package and uncomment the following lines in /etc/php/php.ini :

Sqlite

Install and configure SQLite, then install the php-sqlite package and uncomment the following lines in /etc/php/php.ini :

XDebug

XDebug allows you to easily debug (using modified var_dump function), profile, or trace PHP code.

Install xdebug and uncomment the following line in /etc/php/conf.d/xdebug.ini :

Install php-imap and uncomment the line at /etc/php/php.ini :

Caching

There are two kinds of caching in PHP: opcode/bytecode caching and userland/user data caching. Both allow for substantial gains in applications speed, and therefore should be enabled wherever possible.

OPCache

OPCache comes bundled with the standard PHP distribution, therefore to enable it you simply have to add or uncomment the following line in your PHP configuration file:

A list of its options and suggested settings can be found in its official entry on the PHP website.

archlinux модуль php gettextThis article or section is out of date.archlinux модуль php gettext

Its author recommends a few suggested settings, among which:

Development tools

Commandline tools

archlinux модуль php gettextThis article or section needs language, wiki syntax or style improvements. See Help:Style for reference.archlinux модуль php gettext

Composer

Composer is a dependency manager for PHP. It can be installed with the composer package.

Allow user-wide installations

Box is an application for building and managing Phars. It can be installed with the php-box AUR package.

PDepend

PHP Depend (pdepend) is software metrics tool for php. It can be installed with the pdepend AUR package.

PHP Coding Standards Fixer

PHP Coding Standards Fixer is a PSR-1 and PSR-2 Coding Standards fixer for your code. It can be installed with the php-cs-fixer AUR package.

PHP-CodeSniffer

PHP CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards. It can be installed with the php-codesniffer AUR package.

phpcov

phpcov is a command-line frontend for the PHP_CodeCoverage library. It can be installed with the phpcov AUR package.

phpDox

phpDox is the documentation generator for PHP projects. This includes, but is not limited to, API documentation. It can be installed with the phpdox AUR package.

PHPLoc

PHPLoc is a tool for quickly measuring the size of a PHP project. It can be installed with the phploc AUR package.

PhpMetrics

PhpMetrics provides various metrics about PHP projects. It can be installed with the phpmetrics AUR package.

phptok

phptok is a tool for quickly dumping the tokens of a PHP sourcecode file. It can be installed with the phptok AUR package.

PHPUnit

PHPUnit is a programmer-oriented testing framework for PHP. It can be installed with the phpunit AUR package.

PHPUnit Skeleton Generator

PHPUnit Skeleton Generator is a tool that can generate skeleton test classes from production code classes and vice versa. It can be installed with the phpunit-skeleton-generator AUR package.

Producer

Producer is a command-line quality-assurance tool to validate, and then release, your PHP library package. It can be installed with the producer AUR package.

Troubleshooting

PHP Fatal error: Class ‘ZipArchive’ not found

Ensure the zip extension is enabled.

/etc/php/php.ini not parsed

:_Unable_to_initialize_module»>PHP Warning: PHP Startup: : Unable to initialize module

To fix, find a compatible update for your module, probably by looking up the AUR using its common name.

If it applies, flag the outdated AUR package as outdated.

Источник

Функции gettext

Содержание

User Contributed Notes 37 notes

As some of you have mentioned, you must have the locales compiled on your system first. How this is done is depending on your system/distribution *sigh*

In every case you need to have gettext installed on your system. Users running a Linux with a recent version of libc will have gettext in libc already.

Here’s an example for those of you running Ubuntu Edgy.

First of all, have a look in /usr/share/i18n/SUPPORTED, here are the locales that are supported on your system. To compile a locale we will use the command «locale-gen». («man 8 locale-gen» is good reading)

This command reads configuration from files in the folder /var/lib/locales/supported.d/ In these files the locales and charsets are defined.

If we take swedish as an example, start by creating a file called «sv» in /var/lib/locales/supported.d/ and then put in something like «sv_SE.UTF8 UTF8″ (without the » «) This says that we want the locale sv_SE to be built with charmap UTF-8. Check the file /usr/share/i18n/SUPPORTED for other alternatives.

Now we run «locale-gen» which will compile all locales defined in /var/lib/locales/supported.d/ and put them in /usr/lib/locales (yes that’s a lot of locations. )

Now you’re ready to go.

Create a php-file (e.g. hello.php) where all strings you want to translate are surrounded with _(«string here»);

next run «xgettext hello.php», this creates a file called messages.po, which is you translation-file (pot). Change the «Content-Type: text/plain; charset=CHARSET\n» in this file and replace CHARSET with UTF-8 in this case. Next translate all strings like this.

#: hello.php:3
msgid «hello!»
msgstr «hej!»

This file is then placed in a directory structure somewhere your Apache can read it. The structure looks like this:

Next, let php know what we’re doing. We point to where we have our translations. Add the following at the top of hello.php

This binds the file hello.mo to the locale/ directory you created.
Then set the locale. LC_ALL tells that we want everything translated. Might not be good at all times, as another person here suggested.

Finally select the that we want to use hello.mo

That should be it! Try it out..

If you get any problems try restarting Apache as it seems to cache the locales.

If you are running command line you might have to set the environment variable LANGUAGE to your locale as well. I didn’t have to do that to get it working in apache though, but you might.

What I have found is that setting the LANGUAGE variable (eg. setenv(«LANGUAGE=$locale»)) will allow gettext to search inside your locale directories, even if the locale is not actually valid on the local system.

in response to richard:
i was using the wildcard * for sometime ago without problem, until today.

i use single quotes always if possible, now there are another think to remember.

live2code

Juan Liska, I found an alternative. Instead of renaming or adding a alias to the locale, I simply changed

and it did work fine!

Following three lines take about 0.5 second to execute (Debian, Celeron 2GHz, 256MB RAM):

I think that such delay is important enough to be mentioned in the documentation. In my particular case, it means more than doubled execution time for the entire script.

I’m sure I’ll confuse further, but I feel compelled to chime in. I got stuck on this a bit.

It’s absolutely critical that your gettext installation supports the locale you are trying to use in your setlocale(LC_MESSAGES,$locale) call.

This does not work:

in OpenSUSE 10.2, because /usr/lib/locale does not contain the directory «en» (out of the box), even though your custom LC_MESSAGES domain location might.

In OpenSUSE 10.2, at least, /usr/lib/locale contains for USA English:

It might be possible to set up an alias, I’m not sure (does anyone have a idea about this).

This compelled me to set a configurable default locale (e.g «en_US») in my PHP app, which one probably should do anyway, because HTTP_ACCEPT_LANGUAGE might be blank.

?>

This code was tested on PHP 5.1.4

As stated by robert at klugher dot com:
The environment setting ‘LANGUAGE’ gets priority above any local setting. This means that changing LC_ALL/LC_MESSAGES and LANG as done in almost all examples, won’t do anything.

> stefan+usenet at froehlich dot priv dot at wrote at 5-May-2004 01:30:
> Reading the line
>
>
>
> here over and over again, I have to warn using it, as there are severe caveats.
> For certain locales, LC_NUMERIC swaps period and comma, which may e.g. lead to
> decimals silently stripped of numbers, when inserting rows into an SQL database.
>So DON’T do this, but use
>
>
>
> instead, which does exactly what you want, without any nasty side effecs.

For all Windows-Users:
Be warned the LC_MESSAGES seems to be NOT set on Windows with PHP 5.1.2, so if you develope applications for a Linux-System and want to make it multi-language using gettext, you will get problems using LC_MESSAGES on your Windows-Developement-Box.
You can try to solve this problem by putting a

if you’re having trouble with setlocale (if it’s returning false) on ubuntu or debian:

make sure that the locales taht you want are in the list, if not, add them. for instance, i wanted es_GT (b/c i have an app that must run on redhat and debian, i cant change to es_GT.UTF-8) so, add:

you now have the locales you want, not just the ones the system magically came with

/etc/locales.aliases for «english en_GB.ISO-8859-1» (mentioned before)

/etc/locales.gen for en_GB.ISO-8859-15 ISO-8859-15

I’m not sure if only this entry solved the problem. In my case this entry was made by an dpkg-reconfigure locales (debian), where i created the locales.

Translation only works with de_GE@euro and en_GB.ISO-8859-15 (first column in you locales.gen)

Of course, translation is only interesting if you provide the user with the language and encoding he asks for. Since there’s part of the HTTP protocol that allows you to specify that, it’s nice if one can use that information to pick the ‘right’ translation out of the ones you have available.

Note that even if the user’s browser may support this, the user may not know about it; as such, it’s probably good practice not to remove links to other-languaged versions, so that people can still get a version of your site in another language if they so prefer.

I had a lot of problems getting gettext to work (RedHat 7.3). After reading ALL the comments in this manual, I got it to work OK.

In summary, take care that:

$gettext_domain = ‘messages’;
bindtextdomain($gettext_domain, «/full/path/to/locale»);
textdomain($gettext_domain);

Even though in some cases setlocale() may require a country code in addition to the language code this does not mean that it is required for gettext.

If setlocale() is set to either es_ES or es_MX gettext() will still get the text from a po file in the ‘es’ folder.

It probably is not a good idea to go changing a systems alias file(s) just to avoid the verbosity of the ISO standard because:
a) you might break something
b) your code just lost it’s portability

Note to Chinese programmers.

Took me hours to figure out you cannot use

LANG=zh
but have to use
LANG=zh_TW
on some machines.

a good way to test will be to check the return of setlocale()

1. Restart your webserver. For example by a `systemctl restart apache2`. This will kill already running php processes and reload them afterwards.

One trick I found after HOURS of tries :

You can check the exact info it will use by using putenv() with LANG=. and looking at the return value of setlocale(LC_ALL, «»). The language value your gettext function will use to look for your translation file is the one given for LC_MESSAGES.

I was setting the LANG as fr_BE, and placed the translation file in dirxxx/locale/fr_BE/LC_MESSAGES/.
As it was locale info in my system for fr_BE but NOT LC_MESSAGES, PHP choosed to use the LC_MESSAGES settings for fr_FR instead and then, was looking for a translation file in dirxxx/locale/fr_FR/LC_MESSAGES/. which wasn’t found of course.

So, just make sure to look at the return value of setlocale to see what language value is associated to LC_MESSAGES and, then, to know in which subdirectory the translation file will be looked for by gettext.

For those of you just trying to get a script working and your provider doesn’t support gettext, you can bypass the international stuff by adding this:

Some tips from my Red Hat Linux 7.3 system.

It didn’t work for me until I set a full locale (i.e. es_ES) with setlocale.

I was trying with Michele Manzato’s example (thank you!), but as it sets the language without the country, it was failing for me. Here is the example «fixed» with full locale:

// Change to script directory
// (Not needed in RH 7.3)
$path = dirname(getenv(PATH_TRANSLATED));
chdir($path);

// Set the text domain as ‘mydomain’
$domain = ‘mydomain’;
bindtextdomain(«$domain», «./locale»);
textdomain(«$domain»);

Источник

gettext

(PHP 4, PHP 5, PHP 7, PHP 8)

gettext — Lookup a message in the current domain

Description

Looks up a message in the current domain.

Parameters

The message being translated.

Return Values

Returns a translated string if one is found in the translation table, or the submitted message if not found.

Examples

// Choose domain
textdomain ( «myPHPApp» );

// Print a test message
echo gettext ( «Welcome to My PHP Application» );

// Or use the alias _() for gettext()
echo _ ( «Have a nice day» );
?>

Notes

You may use the underscore character ‘_’ as an alias to this function.

Setting a language isn’t enough for some systems and the putenv() should be used to define the current locale.

See Also

User Contributed Notes 19 notes

If your PO/MO files make use of msgctxt (Context), you’ll be frustrated to find that gettext(msgid) won’t work as you might expect (even if msgid is unique).

In this case, you must use ASCII char 4 [EOT, End Of Text] glued between the msgctxt and msgid.

Example PO content:

msgctxt «Context»
msgid «Test string»
msgstr «Test translation»

msgid «Standard string»
msgstr «Standard translation»

The following will work:

Worth noting is that gettext honors environment variables while selecting the language to use: http://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html

«When a program looks up locale dependent values, it does this according to the following environment variables, in priority order:

Variables whose value is set but is empty are ignored in this lookup. «

In short, if you have non-empty LANGUAGE, you may end up with unexpected localization strings. On the other hand, LANGUAGE can be used to define fallback language if some translation is missing.

Gettext translations are cached. If you change *.mo files your page may not be translated as expected. Here’s simple workaround which does not require restarting webserver (I know, this is just a dirty hack):

for me this works fine (although this is not very elegant solution)

As of php 5.3, you can use the following code to get the preferred locale of the http agent.

on OSX (10.9.3) and PHP (5.4.24) you need to use full local name including codeset

The simplest way to by-pass gettext() cache, without restart apache nor change domain.

Then add one single line before bindtextdomain()

I just wanted to say that gettext won’t work on WAMP Server 2.4 / 64 Bit, see the thread I posted here:

I haven’t tested with only apache 64 Bit, so, I don’t know if the issue is related to apache or WAMP. Anyway, to make it work with WAMP, install the 32 Bit version of WAMP and only do this:

«setlocale» nor setting the LANG, LANGUAGE, and LC_MESSAGES environment variables seems to be necessary under windows. I got it working by setting «LC_ALL» only.

Depending on the implementation of gettext used you might have to call the setlocale(LC_ALL, «») command.
So your example code would be

// Set language to German
putenv ( «LANG=de» );

// Choose domain
textdomain ( «myPHPApp» );

// Print a test message
print ( gettext ( «Welcome to My PHP Application» ));
?>

NOTE: If setlocale returns NULL the LANG specified is invalid and «not supported».

There’s a good tutorial to the GetText tools used with PHP at http://zez.org/article/articleview/42
The only modification I needed to do was to use the correct ISO-language/country-codes (don’t know the ISO number) and call setlocale.
helloworld.php:

print( gettext ( «Hello world!» ));
?>

I had a lot of trouble getting this to work on Red Hat (Yellow Dog) Linux though.

If you come across a situation where the translation works fine on CLI but not on Apache, it may be caused by the Perl Apache module.

$ php7.3 translate.php
Mein deutscher Text.

But not via Apache web server:

$ curl localhost/translate.php
Original English was returned. Something wrong

Disable Perl module and restart Apache:

# a2dismod perl
# systemctl restart apache2

And suddenly the translation works:

$ curl localhost/translate.php
Mein deutscher Text.

The exact reason for this behaviour is (as of right now) unknown to me.

For me it is sufficient to call setlocale() with a string like «nl_BE» as the second parameter, to make gettext() work. Just plain «nl» was not enough.

Ditto when using an environment variable like LANG: «en», «fr», «nl», «de» are not enough: I have to specify the country, too.

So if you are for example using Smarty blocks, make sure that the values given checks if the text has content or else your text will have a bunch of headers printing.

putenv(. ) can cause hidden problems when upgrading or moving between systems which are difficult to diagnose.

On one Linux server we had the following working perfectly with setlocale

We switched servers and found gettext wouldn’t work despite having all the same locale files and settings

The recommendation to switch to

didn’t fix the problem.

did. So if you have problems, check all three settings.

If like me, you are stuck with making a lot of code localizable, you have to go through all your php files and wrap all srings in _(«string»). Here’s an elisp function which can help you out.

The shortcut C-k can be used for translating parts of php strings which contain html tabs. We dont want to translate the entire string including the tabs, so we highlight just the substring that needs to be translated and use C-k.

Code
;author: Vinay Kuruvila March 01 2006
;updated to handle php strings containing html tabs

;makes the text starting at left and ending at right in the
;current buffer a localizable string, assuming that the
;string is within php context
(defun make-localizable-string-in-php-context(left right)
(goto-char left)
(insert «_(«)
(goto-char (+ right 2))
(insert «)»)
)

;makes the highlighted text a localizable string
;uses php-context localization if the first char highlighted
;is » or ‘
;otherwise uses html-context localization
(defun make-localizable-string()
(interactive)

;find the positions of the left and right ends of
;the highlighted text
(if (> (point) (mark))
(progn
(setq right (point))
(setq left (mark))
)
(progn
(setq right (mark))
(setq left (point))
)
)

;to handle php strings which contain html tabs
;we dont want to translate the html tabs
(defun make-localizable-string-within-php-string ()
(interactive)

;find the positions of the left and right ends of
;the highlighted text
(if (> (point) (mark))
(progn
(setq right (point))
(setq left (mark))
)
(progn
(setq right (mark))
(setq left (point))
)
)
(goto-char left)
(insert «\». _(\»»)
(goto-char (+ right 6))
(insert «\»).\»»)
(deactivate-mark)
)

;assigns a keyboard shortcut
(global-set-key «\C-l» ‘make-localizable-string)
(global-set-key «\C-k» ‘make-localizable-string-within-php-string)

Источник

Gettext

User Contributed Notes 12 notes

How to use gettext on Windows.

If you use Linux start from the step 2 and consider cmd as linux shell.

Check all options during the installation and go on.

2] Create a index.php file into your website directory with this code inside:

echo _ ( «Good Morning» );
?>

3] Open cmd and move into your website folder using cd

5] Once finished will be generate a file called messages.mo. Now you have to set the language and the charset. Open messages.mo with notepad and edit the lines:

— «Language: \n» BECOMES «Language fr\n»
— «Content-Type: text/plain; charset=CHARSET\n» BECOMES «Content-Type: text/plain; charset=UTF-8\n»

6] Remember to translate every line where is present msgstr «», translating the instance msgid into language you have chosen. For instance:

#: index.php:2
msgid «Good Morning»
msgstr «Bonjour»

7] Once finished open cmd and move into your website folder using cd and then type
msgfmt messages.po

8] Now you have to create a folder structure like this into your website folder. Do this for each language you want to add.

9] Move messages.mo and messages.po in locale/fr_FR/LC_MESSAGES

10] Now edit the index.php as follows

echo _ ( «Good Morning» );
?>

11] Open index.php in your browser and if you will see «Bonjour» it means everything is okay. If not, start from the step 2 again.

If it was usefull for you vote up!

So this machine only has English and Japanese! To add eg. Finnish, install the package:

sudo apt-get install language-pack-fi-base

Adjust your po paths so that they match, e.g. «./locale/fi_FI.utf8/LC_MESSAGES/messages.po».

Now restart Apache, and it should finally work. Figuring this out took quite a while.

My PHP app was made for UTF-8 but i had a problem that gettext always returned all texts in ISO-8859-2 instead of UTF-8.

Then i found out that you have to set locale in PHP exactly to encoding you request. So when i wanted czech UTF-8 i used:

And what about pgettext and npgettext? They are there in the gettext documentation, but there aren’t in PHP. They’re very useful if you have the same messages for translation, but in different contexts, so they should be translated separately and probably differently.

Here’s my «emulated» pgettext() function:

if (! function_exists ( ‘pgettext’ )) <

>
?>

By default, xgettext doesn’t support pgettext function for PHP source files. But there is a parameter which can work-around it. Here’s how I call xgettext:

In sourceFile.php I use the following test code:

pgettext(‘menu’, ‘Open’); //Substitute «Otwórz»
pgettext(‘forum’, ‘Open’); //Substitute «Otwarty», different context

msgctxt «menu»
msgid «Open»
msgstr «Otwórz»

msgctxt «forum»
msgctxt «Open»
msgstr «Otwarty»

I’ve tested it out and everything works fine 🙂 If anyone have some further suggestions or fixes, please write 😉

«Content-Type: text/plain; charset=UTF-8\n»

Because of this I’ve wasted a lot of time debugging my code, testing every single little changes people suggested over this manual and Internet:

//this:
putenv ( «LANG=pt_BR.utf8» );
//or this:
putenv ( «LANGUAGE=pt_BR.utf8» );

Finally, the code which brought the right translated strings (also with the correct charset) was:

= dirname ( __FILE__ ). ‘/locale’ ;
$domain = ‘mydomain’ ;
$locale = «pt_BR.utf8» ;

//putenv(«LANG=».$locale); //not needed for my tests, but people say it’s useful for windows

I hope to help someone else not to waste as much time as I’ve wasted. =P

Using:
Ubuntu 8.04 (hardy)
Apache 2.2.8
PHP 5.2.4-2ubuntu5.6

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *