Skip to content

Instantly share code, notes, and snippets.

@mpdroog
Created February 9, 2021 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpdroog/f746d4f72c47d535e03d6319360fa87a to your computer and use it in GitHub Desktop.
Save mpdroog/f746d4f72c47d535e03d6319360fa87a to your computer and use it in GitHub Desktop.
<?php
/**
* PO to JSON.
*/
$lang = "fr";
$lines = explode("\n", file_get_contents(__DIR__ . "/text.po"));
array_shift($lines); array_shift($lines); // Ignore first two lines
$out = [];
function nextline() {
global $lines;
if (count($lines) === 0) {
return false;
}
next:
$line = array_shift($lines);
if ($line === null) return false;
$line = trim($line);
if (strlen($line) === 0) goto next; // empty line
$cmd = substr($line, 0, strpos($line, " "));
if (substr($line, 0, 1) === '"') goto next; // comment "xxxx"
$line = substr($line, strlen($cmd)+1);
return [$cmd, $line];
}
$keygroups = [];
while(true) {
$res = nextline();
if ($res === false) break;
list($cmd, $line) = $res;
if ($cmd === '#:') {
$keys = explode(".", explode(":", $line)[1]);
if (count($keys) === 1) {
var_dump($line, $keys); die("ERR");
}
array_shift($keys); array_shift($keys); // strip off translation.json
$keygroups[] = $keys;
}
if ($cmd === "msgstr") {
// Step in array
foreach ($keygroups as $keys) {
$last = &$out;
foreach ($keys as $i => $key) {
$is_val = $i+1 === count($keys);
if ($key === "ppf") {
if (! isset($last[$key])) $last[$key] = [];
$last = &$last[$key];
// combine remaining
$key = implode(".", array_slice($keys, $i+1));
$is_val = true;
}
if ($is_val) {
$last[$key] = mb_substr($line, 1, mb_strlen($line)-2); // set value without ""
break;
} else {
// one deeper
if (! isset($last[$key])) $last[$key] = [];
$last = &$last[$key];
}
}
}
$keygroups = []; // reset
}
}
file_put_contents(__DIR__ . "/translation.json", json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment