Программа для перевода php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

This library permits you to easily create translations for PHP scripts and apps.

License

DamienVauchel/php-translator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Simple and light PHP translator

This library permits you to easily create translations for PHP scripts and apps.

You can install the package with git clone and composer install in the directory.

Or you can directly use composer :

composer require scoobydam/php-translator

This library is an easy-to-use and light one.

use ScoobyTranslator\Translator\Translator; $translator = new Translator(__DIR__ . '/translations', 'fr'); $translator->translate('key_to_translate');

This example will search for a fr.php file in the dir you passed the path in the first parameter.
This file might be like following

 // __DIR__/translations/fr.php $translations = [ 'general' => [ 'key' => 'value', ], ];

It needs to define the $translations variable and at least the general context key.

To know all what you can do, you can find full documentation here.

You can send PRs if you want to 🙂

About

This library permits you to easily create translations for PHP scripts and apps.

Источник

Консольный Google переводчик на PHP

В поисках по-настоящему удобного переводчика, решение написать свой, думаю, никого не удивит.

Для начала, определим функции, которые нам понадобятся.

1. get_with_curl — с этой все понятно: мы ей $url , а она нам $response от сервера:

function get_with_curl($url) < $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12'); $response = curl_exec($ch); if (curl_errno($ch)) < return curl_error($ch); >else < curl_close($ch); return $response; >> 

2. cleanup_response — кто бы мог подумать, что Google будет отдавать невалидный json . Сплошь и рядом какие-то левые запятые. Эту неприятную неожиданность приходится исправлять регулярками. Пока хватает вот таких вот:

function cleanup_response($response) < $response = preg_replace('/,+/', ',', $response); $response = preg_replace('/\[,/', '[', $response); return $response; >

3. print_line — вот с ней пришлось повозиться. Не знаю как в *nix, а вот чтоб сделать echo из PHP скрипта в консоль windows, нужно гуглить и подбирать кодировки часа два. (Не забудьте установить в качестве консольного шрифта какой-нибудь TrueType, например Lucida Console):

4. Параметры, передаваемые в API. Вот здесь есть где разогнаться для расширения скрипта. Меня же конкретно интересует перевод с английского на русский. Ну и еще синонимы (для общего развития):

$params = [ "client" => "t", "sl" => "en", // исходный язык "tl" => "ru", // язык, на который нужно перевести "hl" => "ru", // язык сообщений от API "dt" => "bd", // получать синонимы "q" => $term, ]; 

Еще важно задать alias для запуска скрипта в консоли (чтоб каждый раз не вводить весь путь к скрипту)

cd ~ echo "alias pt='php //translate.php'" >> .bashrc 

Небольшая демонстрация работы скрипта:

Конечно же, можно сделать этот скрипт еще лучше. Вот только я старался сделать его максимально простым.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

License

delfimov/Translate

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

translate fails for plural defined translations

Git stats

Files

Failed to load latest commit information.

README.md

SensioLabsInsight

Easy to use i18n translation PHP class for multi-language websites with language auto detection and plurals.

PSR-6 translation containers. PSR-3 logger.

Add this line to your composer.json file:

composer require delfimov/translate

Alternatively, copy the contents of the Translate folder into one of your project’s directories and require ‘src/Translate.php’; , require ‘src/Loader/LoaderInterface.php’; , require ‘src/Loader/PhpFilesLoader.php’; If you don’t speak git or just want a tarball, click the ‘zip’ button at the top of the page in GitHub.

See example directory for sources.

 use DElfimov\Translate\Translate; use DElfimov\Translate\Loader\PhpFilesLoader; use Monolog\Logger; // PSR-3 logger, not required use Monolog\Handler\StreamHandler; $log = new Logger('Translate'); $log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); $t = new Translate( new PhpFilesLoader(__DIR__ . "/messages"), [ "default" => "en", "available" => ["en", "ru"], ], $log // optional ); $num = rand(0, 100); $t->setLanguage("en"); // this is not required, language will be auto detected with Accept-Language HTTP header echo $t->t('some string') . "\n\n"; // or $t('some string'); echo $t->plural('%d liters', $num) . "\n\n"; echo $t->plural("The %s contains %d monkeys", $num, ['tree', $num]) . "\n\n"; $num = rand(0, 100); $t->setLanguage("ru"); echo $t->t('some string')."\n\n"; // or $t('some string'); echo $t->plural('%d liters', $num) . "\n\n"; echo $t->plural("The %s contains %d monkeys", $num, ['tree', $num]) . "\n\n"; ?>pre>
 return [ 'some string' => 'Some string', '%d liters' => ['%d liter', '%d liters'], '%d liters alt' => '%d liter|%d liters', 'The %s contains %d monkeys' => ['The %s contains %d monkey', 'The %s contains %d monkeys'], 'The %s contains %d monkeys alt' => 'The %s contains %d monkey|The %s contains %d monkeys', ];
 return [ 'some string' => 'Просто строка', '%d liters' => '%d литр|%d литра|%d литров', 'The %s contains %d monkeys' => ['На %s сидит %d обезьяна', 'На %s сидят %d обезьяны', 'На %s сидят %d обезьян'], 'The %s contains %d monkeys alt' => 'На %s сидит %d обезьяна|На %s сидят %d обезьяны|На %s сидят %d обезьян', 'tree' => 'дереве' ];

Источник

How to Master the Translation of PHP Apps

How to translate php apps. This post reviews the available solutions. Make your application available in various languages.

Software localization blog category featured image | Phrase

Despite alternative web programming languages like Ruby (on Rails), Python or NodeJS dominating the industry headlines, PHP remains a popular choice for building web applications.

Despite this fact, there is still no real standard solution for localizing PHP applications.

Building a truly international application is not just about translating strings. Other issues to consider are date and time formats, currency symbols and pluralization. Programmers often underestimate the complexity of localization and get stuck with homemade code that is a pain to maintain. So, let’s talk about PHP Arrays, gettext, frameworks, and Intl.

PHP Arrays

Associative Arrays have been the primitive approach of many big and small PHP projects for a long time. Translatable strings are stored in an associative array, one file per language.

The appropriate language file is loaded at the beginning of your application code:

This approach is simple and easy to use, but it quickly reaches its limits. Consider an application that displays a notification when the user uploads files:

3 files uploaded successfully

What if it was only one file? Maybe do this:

1 file(s) uploaded successfully

Nah! That’s just plain ugly. I could come up with a hack like:

Not only does this clutter up the code, it doesn’t really solve the problem. In the English language appending a ‘s’ is enough, but pluralization works differently in other languages. For example, the pluralization of the world “file” (plik) in the Polish language works like this:

1 plik 2,3,4 pliki 5-21 pliko'w 22-24 pliki 25-31 pliko'w

gettext

The GNU gettext system has been around for more than 20 years. It is widely used and is the de-facto standard for localization in many programming languages.

Using gettext with PHP can be tricky in some setups.

If you are running a stock Ubuntu VPS, gettext will only support the locales installed on the machine. Or perhaps you are on a hosting plan where the gettext extension isn’t available.

In both cases, php-gettext can help. php-gettext it is a drop-in replacement for PHP enviroments where the gettext extension isn’t installed.

Basic Setup

In this example, i want to use English and German. I create the following directory structure:

index.php /locale /en_US /LC_MESSAGES messages.po messages.mo /de_DE /LC_MESSAGES messages.po messages.mo

Translations are stored in .po files, a simple plain-text file format. Using just a text editor I create en/LC_MESSAGES/messages.po:

msgid "hello" msgstr "Hello" msgid "signup" msgstr "Sign up for free"

I also create a messages.po for the de_DE locale:

msgid "hello" msgstr "Hallo" msgid "signup" msgstr "Kostenlos registrieren"

In the next step, .po files are compiled to .mo files. This can be done using the msgfmt command line utility:

msgfmt messages.po -o messages.mo

This is done for each .po file.

Usage

I can now use the .mo files via gettext in my PHP app:

This script creates a new gettext enviroment using the de_DE locale. Then the message with the id ‘hello’ is echo’ed which will output the german “Hallo”.

The gettext system supports plural forms. Using the example from above, I create a plural msgid:

sgid "upload" msgid_plural "uploads" msgstr[0] "file uploaded successfully" msgstr[1] "files uploaded successfully"

which I can use in my app code:

gettext can handle pluralization but it has no tools for working with numbers, currency, date/time formats.

Frameworks

All major PHP frameworks have built-in support for creating translations. Some offer additional features such as classes for currency and date/time formatting.

Language files Plurals Date/Time Currency
Symfony YAML, XLIFF, PHP Arrays
F3 PHP Arrays, INI
CodeIgniter PHP Arrays
Kohana PHP Arrays
CakePHP gettext
Zend PHP Arrays, CSV, TBX/TMX, gettext, Qt, XLIFF, INI, .

The localization modules of these frameworks can be used as a standalone tool without a lot of overhead code from the framework itself. Check out our other tutorials to see what that could potentially look like:

And of course, let's not forget about Laravel, one of the most popular PHP frameworks:

4. Intl

PHP 5.3 introduces the Intl class. Intl is a set of convenient helpers for formatting dates, time, numbers and working with currency. It can be used to complement gettext or frameworks that lack some of the functionality.

Conclusion

Localization can sometimes seem hard. Fortunately, you don’t have to try to solve the problems with homemade code.

Unfortunately, gettext doesn’t play very smoothly with PHP so I'd recommend using a framework.

Symfony, Zend, and F3 all do a great job and are easy to use. After playing around with all the frameworks, I really like the F3 approach. Here's a step-by-step guide on getting started with F3.

Last updated on October 28, 2022.

Источник

Читайте также:  Почему python называется python
Оцените статью