Simple method to make a site multi-lingual in PHP

Simple method to make a site multi-lingual in PHP admin 11 July, 2009 - 18:36

Firstly do this from the start of the project - it's a lot easier and quicker than editing at the end.

Wherever you need text that is to be translated use the simple sequence ~PHnnnn~, where nnnn is a four digit number. It slows you down a little at first - however the benefits later on are massive - for one thing you can edit the English text and you therefore get a simple CMS for free.

For example:

    phrase_op("<h1>~PH2228~</h1>");

phrase_op is a simple routine that takes phrases from a database and replaces all of the tokens found.

/**
 * outputs a string changing all the ~PH####~ into the corresponding phrase
 */
function phrase_op($txt)
{
    preg_match_all("/\~PH[0-9][0-9][0-9][0-9]\~/",$txt,$regs,PREG_SET_ORDER);
        foreach($regs as $result) {
        $phc = substr($result[0],1,strlen($result[0])-2);
        $ph = get_phrase($phc);
        $txt = str_replace($result[0],$ph,$txt);
    }
    echo $txt;
}


function load_phrases()
{
    global $phrases;
    global $config;

    $phrases = array();

    $sql = "SELECT * FROM tb_phrases where iso='".mysql_real_escape_string($config['cur_lang'])."'";

    $result = mysql_query($sql) or die('exec_query failed: [ '.$sql.' ]'.mysql_error());

    while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
    {
        $phrases[$row['phrase_code']] = $row['text'];
    }
}

All you need to do now is to create the sql to create the phrases, and a quick page to allow editing.