Extract gettext translations from PHP heredoc syntax?

I am using PHP gettext to do localization. I use Poedit for the actual translation, and with its function "Update from sources" it is really easy to extract all the lines that need to be translated, except for the internal heredoc syntax.

Poedit uses the xgettext program to generate .po files from PHP source files. And it works great when the PHP code looks like this:

echo "<h1>". _("test") ."</h1>"; 

But the following is not retrieved (note that you need to use a pseudo-t-object):

 echo <<<EOD <h1>{$->_('test')} EOD; 

In PHP code, you can solve this problem as follows:

 <?php $t = _('test'); echo <<<EOD <h1>$t</h1> EOD ?> 

But I really would prefer the xgettext program to be able to extract a string from the heredoc block.

A workaround for this was suggested in the comments of the PHP documentation. A workaround is to use the xgettext program to process the PHP source files as Python code. But using this approach in Poedit gives me a lot of syntax errors from the xgettext parser.

Does anyone know a workaround for getting xgettext to extract translations from PHP heredoc syntax?

A somewhat related ticket was opened in the gettext ticketing system: http://savannah.gnu.org/bugs/?27740 This indicates that heredoc syntax support may be improved

+4
source share
1 answer

I am a gettext ticket reporter that you refer to in your post. When I sent the ticket, I had something completely different, something more in these areas:

 <?php $msg = _(<<<TXT He said: "Hello world!". TXT ); ?> 

Gettext cannot extract text from such heredoc / nowdoc lines, but it can be really useful when translating large chunks of text.

In my case, I use gettext in the CLI PHP script to translate text fragments containing XML markup. This markup is part of the source text and must also be translated. To manually avoid every quote or apostrophe in the markup, messages are pretty hard to read in POedit or any other editor.

In your case, it seems that you want the interpolated code in the lines (heredoc / nowdoc) to be extracted. You can easily solve this problem by preparing the text before the actual interpolation:

 <?php $t = _('test'); echo <<<EOD <h1>$t</h1> EOD ?> 

I do not think this should be considered a mistake, because the exact equivalent of the code you posted using the heredoc syntax would be as follows:

 <?php echo "<h1>{$t->_('test')}</h1>"; ?> 

from which gettext cannot extract the message "test".

+3
source

Source: https://habr.com/ru/post/1300715/


All Articles