locallang-xml-to-xliff/index.php

123 lines
3.4 KiB
PHP
Raw Normal View History

2024-02-12 11:52:17 +01:00
<?php
function Language2XML($data, $language, $translations = array()) {
$xml = new DOMDocument('1.0', 'UTF-8');
$xliff = $xml->createElement('xliff');
$xliff->setAttribute('version', '1.2');
$xliff->setAttribute('xmlns', 'urn:oasis:names:tc:xliff:document:1.2');
$file = $xml->createElement('file');
$file->setAttribute('source-language', 'en');
if (func_num_args() > 2) {
$file->setAttribute('target-language', $language);
}
$file->setAttribute('datatype', 'plaintext');
$file->setAttribute('original', 'messages');
$file->setAttribute('date', strftime('%Y-%m-%dT%H:%M:%SZ'));
$file->setAttribute('product-name', 'zsb');
$header = $xml->createElement('header');
$file->appendChild($header);
$body = $xml->createElement('body');
foreach ($data as $index => $label) {
$unit = $xml->createElement('trans-unit');
$unit->setAttribute('id', $index);
$unit->setAttribute('resname', $index);
$unit->setAttribute('approved', 'yes');
$unit->setAttribute('xml:space', 'preserve');
$source = $xml->createElement('source', $label);
$unit->appendChild($source);
if (func_num_args() > 2) {
$target = $xml->createElement('target', $translations[$index]);
$unit->appendChild($target);
}
$body->appendChild($unit);
}
$file->appendChild($body);
$xliff->appendChild($file);
$xml->appendChild($xliff);
$xml->formatOutput = true;
return $xml->saveXML();
}
$outputs = [];
if (isset($_POST['xml'])) {
$xml = $_POST['xml'];
$xml = utf8_encode($xml);
$doc = new DOMDocument();
$doc->loadXML($xml);
$defaults = array();
$langs = array();
$xpath = new DOMXPath($doc);
$languages = $xpath->query("//T3locallang/data/languageKey");
foreach ($languages as $language) {
$lang = $language->attributes['index']->value;
if ($lang !== 'default') {
$langs[$lang] = array();
}
foreach ($language->childNodes as $word) {
if ($word->nodeName !== 'label') {
continue;
}
$string = utf8_decode($word->attributes['index']->value);
$translation = utf8_decode($word->nodeValue);
if ($lang === 'default') {
$defaults[$string] = $translation;
} else {
$langs[$lang][$string] = $translation;
}
}
}
$outputs = array(
'locallang.xlf' => Language2XML($defaults, 'en'),
);
foreach ($langs as $lang => $words) {
$outputs[$lang . '.locallang.xlf'] = Language2XML($defaults, $lang, $words);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>LocalLang: XML to XLIFF</title>
<style>
textarea {
box-sizing: border-box;
height: 250px;
width: 100%;
}
</style>
</head>
<body>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<fieldset>
<legend>Input locallang.xml</legend>
<textarea name="xml" style="width: 100%; height: 250px;"><?= htmlspecialchars(@$_POST['xml']) ?></textarea>
</fieldset>
<footer>
<input type="submit">
</footer>
</form>
<?php
foreach ($outputs as $file => $xml) {
echo('<h2>' . $file . '</h2>');
echo('<textarea onfocus="this.select()">'. htmlspecialchars($xml) .'</textarea>');
}
?>
</body>
</html>