geekwright / po
辅助读取、操作和创建 GNU gettext 风格 PO 文件的对象
v2.0.2
2020-12-30 23:34 UTC
Requires
- php: >7.1
Requires (Dev)
- phpunit/phpunit: ^7.0|^8.0
- smarty/smarty: ^3.1
README
Po 是一组辅助读取、操作和创建 GNU gettext 风格 PO 文件的对象。
安装
推荐安装方法是使用 composer。要将 "geekwright/po" 添加到您的 composer 管理项目,请使用此命令
composer require geekwright/po
PHP 支持
Po 版本 1 支持 PHP 5.3 及以上。从版本 2 开始,Po 至少需要 PHP 7.1。
命名空间
所有 Po 类都位于 Geekwright\Po
命名空间中。
示例
Po 提供创建、读取和修改 PO 和 POT 文件的能力,包括从 PHP 源代码扫描 gettext 风格调用以构建 POT 文件的能力。您可以根据需要连接各个部分,但这里有一些常见情况的示例。
读取 PO 文件
try { $poFile = new PoFile(); $poFile->readPoFile('test.po'); // list all the messages in the file $entries = $poFile->getEntries(); foreach($entries as $entry) { echo $entry->getAsString(PoTokens::MESSAGE); } } catch (UnrecognizedInputException $e) { // we had unrecognized lines in the file, decide what to do } catch (FileNotReadableException $e) { // the file couldn't be read, nothing happened }
获取 Plural-Forms 标头
$pluralRule = $poFile->getHeaderEntry()->getHeader('plural-forms');
添加新条目
$entry = new PoEntry; $entry->set(PoTokens::MESSAGE, 'This is a message.'); $entry->set(PoTokens::FLAG, 'fuzzy'); $poFile->addEntry($entry);
获取条目的翻译
条目的翻译可以是一个字符串,如果条目是复数形式,则可以是一个字符串数组。以下代码片段将根据情况将翻译分配给 $msgstr
。
$msgid_plural = $entry->get(PoTokens::PLURAL); if (empty($msgid_plural)) { $msgstr = $entry->getAsString(PoTokens::TRANSLATED); } else { $msgstr = $entry->getAsStringArray(PoTokens::TRANSLATED); }
写入 PO 文件
try { $poFile->writePoFile('test.po'); } catch (FileNotWriteableException $e) { // the file couldn't be written }
从 PHP 源代码创建 POT 文件
$poFile = new PoFile(); $poInit = new PoInitPHP($poFile); foreach (glob("*.php") as $filename) { try { $poInit->msginitFile($filename); } catch (FileNotReadableException $e) { // the souce file couldn't be read, decide what to do } } try { $poFile->writePoFile('default.pot'); } catch (FileNotWriteableException $e) { // the file couldn't be written }
API
有关更多信息,请参阅完整的 Po API 文档。