Tuesday, January 26, 2010

Convert PHP source file to PO file

I have written a simple code for generating PHP source code to PO file. I hope it may help you.

Here $file is your php file path (ex c:/my_file/test.php) with message content as __('your message in php code');

$msg_lines = "";
$po_obj = new POContent();
$po_obj->generatePoContent($file,$msg_lines);

#write po file content
$po_strings = "";
foreach($msg_lines as $msgid => $line_contents)
{
$po_strings .= "# Translator comments\r\n";
$po_strings .= "#. Programmer comments\r\n";
foreach($line_contents['line'] as $key => $line)
$po_strings .= "#: ".$line."\r\n";
$po_strings .= "msgid \"".$msgid."\"\r\n";
$po_strings .= "msgstr ''\r\n";
$po_strings .= "\r\n";
}

$po_file_path = 'c:/my_file/test.po';
$fh = fopen($po_file_path,'wb');
if (!$fh) {
echo __('PO File generation failed');
}
else{
fwrite($fh,$po_strings);
fclose($fh);
echo __('PO File generated successfully');
}

class POContent{
/**
* Generate PO File by reading entire particular component's source file
* @param $file String (PHP Source file path to parse)
* @param $msg_lines String (Refrence variable to store all the msgid)
* @return
*/
function generatePoContent($file,&$msg_lines){
//open source file
$datas = file($file);
$msg_file = basename($file);
$pattern ="/__\([\"\']([^()]+)[\"\']\)/";

foreach($datas as $indx => $data){
$msgs = "";
preg_match($pattern, $data, $msgs);
if(count($msgs) > 0){
if(!array_key_exists($msgs[1],$msg_lines)){
$msg_lines[$msgs[1]]['file'][$msg_file] = $msg_file.":Line No.".($indx+1);
$msg_lines[$msgs[1]]['line'][] = $msg_file.":Line No.".($indx+1);
}
else{
$temp_line = $msg_lines[$msgs[1]]['file'][$msg_file];
if(!array_key_exists($msg_file,$msg_lines[$msgs[1]]['file'])){
$msg_lines[$msgs[1]]['file'][$msg_file] = $msg_file.":Line No.".($indx+1);
$msg_lines[$msgs[1]]['line'][] = $msg_file.":Line No.".($indx+1);
}
else{
$msg_lines[$msgs[1]]['file'][$msg_file] = $temp_line.",".($indx+1);
$msg_lines[$msgs[1]]['line'][count($msg_lines[$msgs[1]]['line'])-1]=$temp_line.",".($indx+1);
}
}
}
}
}
}

Now You can check the c:/my_file/test.po

No comments:

Post a Comment