Monday 25 July 2011

Quicktip – Convert .po files to .php (PHP array)

Multilanguage websites or webapplications are state-of-the-art today. You have a lot of choices in translation technology, language, format, etc. gettext is one of the most popular libraries to use. There are some downsides using gettext. One of the bad things is that you need to compile your .po files to .mo files before deployment. So, I decided to use PHP arrays instead of .po files for my translation strings. In order to convert my existing .po files, I wrote a little 5-minute script :-), which prints out a php file with a php array, according to the .po file.

<?php

$file = '/data/workspaces/tutorial/portal/lang/de_DE/LC_MESSAGES/portal.po';
$translations = array();
$po = file($file);
$current = null;
foreach ($po as $line) {
    if (substr($line,0,5) == 'msgid') {
        $current = trim(substr(trim(substr($line,5)),1,-1));
    }
    if (substr($line,0,6) == 'msgstr') {
        $translations[$current] = trim(substr(trim(substr($line,6)),1,-1));
    }
}

echo "<?php\n\n";
foreach ($translations as $msgid => $msgstr) {
    echo "$lang['" . $msgid . "'] = '" . $msgstr . "';\n";
}
echo "\n?>";

?>
This prints out something like
<?php

$lang['January'] = 'Januar';
$lang['February'] = 'Februar';
$lang['March'] = 'März';
$lang['April'] = 'April';

?>

No comments:

Post a Comment