Monday, February 8, 2010

PHP Generating MO Language file from PO file

/**
* Generate Mo File from an array generate by PO file
* @param Object $file PO file path with file name
* @param String $msgid_key msgid key in PO file
* @param String $msgid_value msgstr value for above msgid
* @param String $mo_file mo file path
* @return boolean
*/
function writePo($file,$msgid_key,$msgid_value,$mo_file){

$fd = fopen($file->filepath, "r+b"); // File will get closed by PHP on return
if (!$fd) {
$msg = sprintf(__('The file %s could not be open for write'),$file_name);
//do whatever you want with this error msg
return FALSE;
}

$context = "MSGID";
$lineno = 0;
$wflag = false;
while (!feof($fd)) {

$line = fgets($fd, 10*1024); // A line should not be this long

if ($lineno == 0) {
// The first line might come with a UTF-8 BOM, which should be removed.
$line = str_replace("\xEF\xBB\xBF", '', $line);
}
$lineno++;
$line = trim(strtr($line, array("\\\n" => "")));

if (!strncmp("msgid", $line, 5) && $context = "MSGID") {
$line = trim(substr($line, 5));
$quoted = $this->_parse_quoted($line);
if ($quoted === FALSE) {
$msg = sprintf(__('The PO file %s contains a syntax error on %d line'),$file->filename,$lineno);
//do whatever you want with this error msg
return FALSE;
}
if($quoted == $msgid_key){
$wflag = true;
$context = "MSGSTR";
}
}
if (!strncmp("msgstr", $line, 5)) {

if($context == "MSGSTR" && $wflag == true){
fclose($fd);
$wflag = false;
//write msgdtr value to file
$msg = "msgstr ".'"'.$msgid_value.'"';
$lines = file($file->filepath);
$lines[$lineno-1] = $msg . "\r\n";
// Turn array back into a string to write to file
$data = implode('',$lines);
$fp = fopen($file->filepath,'wb');
fwrite($fp,$data);
fclose($fp);

//generate mo file
if(file_exists($mo_file)){
$mo_lines = file($mo_file);
foreach($mo_lines as $key => $value){
if(strlen(strstr($value,$msgid_key)) > 0){
$mo_lines[$key] = "'".addslashes($msgid_key)."' =>".$msgid_value.",\r\n";
$data = implode('',$mo_lines);
$fm = fopen($mo_file,'wb');
fwrite($fm,$data);
fclose($fm);
return true; //found msg key then return
}
else if(strlen(strstr($value,");")) > 0 ){
$mo_lines[$key] = "'".addslashes($msgid_key)."'=>".$msgid_value.",\r\n";
$mo_lines[] = ");";
$data = implode('',$mo_lines);
$fm = fopen($mo_file,'wb');
fwrite($fm,$data);
fclose($fm);
return true;
}
}
}
else {
$data = "#do not touch this file. This is machine generated fie.\r\n#Changes in file structure may cause file parsing error.\r\n\r\n";
$data .= '$translation = Array('."\r\n";
$data .= "'".addslashes($msgid_key)."'=>".$msgid_value.",\r\n";
$data .= ");";
$fm = fopen($mo_file,'wb');
fwrite($fm,$data);
fclose($fm);
}
}
}
}
return true;
}

No comments:

Post a Comment