【问题标题】:export .po file into .csv将 .po 文件导出为 .csv
【发布时间】:2013-12-26 21:51:00
【问题描述】:

我正在寻找一种从 .po 本地化文件创建 excel 或 CSV 文件的简单方法。

我无法通过 Google 找到任何内容,所以我正在考虑自己用 PHP 编写它。 PO文件有这样的结构

msgstr "名称" msgstr "标题"

所以我想我需要我的 PHP 脚本来解析 .po 文件以查找“每次出现关键字 msgstr 后逗号之间的第一位文本”。

我认为这是正则表达式的工作,所以我尝试了,但它没有返回任何内容:

$po_file = '/path/to/messages.po';

if(!is_file($po_file)){
    die("you got the filepath wrong dude.");
}

$str = file_get_contents($po_file);
// find all occurences of msgstr "SOMETHING"
preg_match('@^msgstr "([^/]+)"@i', $str, $matches);
$msgstr = $matches[1];

var_dump($msgstr);

【问题讨论】:

  • 你需要捕捉评论行吗?

标签: php regex csv po


【解决方案1】:

有一个不错的梨图书馆。 File_Gettext

如果您查看源代码 File/Gettext/PO.php,您会看到您需要的正则表达式模式:

$matched = preg_match_all('/msgid\s+((?:".*(?<!\\\\)"\s*)+)\s+' .
                          'msgstr\s+((?:".*(?<!\\\\)"\s*)+)/',
                          $contents, $matches);

for ($i = 0; $i < $matched; $i++) {
    $msgid = substr(rtrim($matches[1][$i]), 1, -1);
    $msgstr = substr(rtrim($matches[2][$i]), 1, -1);

    $this->strings[parent::prepare($msgid)] = parent::prepare($msgstr);
}

或者只使用 pear 库:

include 'File/Gettext/PO.php';

$po = new File_Gettext_PO();
$po->load($poFile);
$poArray = $po->toArray();

foreach ($poArray['strings'] as $msgid => $msgstr) {
    // write your csv as you like...
}

【讨论】:

  • 但是,请注意,该模式将因以下字符串而失败:msgstr "abc\\\"def"
  • @CasimiretHippolyte 如果你真的发现了一个错误,你应该写信给PEAR bug tracker
  • 对不起,我搞错了!它将失败:msgstr "abcdef\\"
  • 我无法使 PEAR 解决方案工作,但第一种方法工作正常,稍作调整。谢谢!
猜你喜欢
  • 2017-01-08
  • 2014-05-12
  • 2019-04-18
  • 1970-01-01
  • 2018-11-12
  • 2018-11-09
  • 2011-10-04
  • 2016-03-01
  • 1970-01-01
相关资源
最近更新 更多