简体   繁体   中英

PHP use gettext to translate an array

I have a web page in PHP and I'm translating with gettext _("STRING_TO_TRANSLATE") .

I have in my DB one table with all user profiles for my website. I put them in a selection box to choose one.

Now I want to translate the profile names.

Is there ANY way to translate (USING GETTEXT) the profile names coming from database?

Code example of my selection box:

while($row = mysqli_fetch_array($result_user_type))
{
    echo "<option $selected value=\"".$row['id']."\">".$row['designation']." </option>";
}   

Wouldnt you just do...

while($row = mysqli_fetch_array($result_user_type))
{
   echo "<option $selected value=\"".$row['id']."\">"._($row['designation'])." </option>";
}   

Im not sure though, never used gettext or anything but if its just a function that takes an argument and returns a translated string, then this should do it.

You just can't translate PHP variables! The gettext doesn't execute PHP, it just scans your code to get plain strings.

You should look this for example http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/

Cheers

To translate my user_type array I created a class that prints the result from the DB to a file translate.php :

public function createArrayType()
{
    $filePHP   = fopen("translate.php", "a");
    $initial = true;

    if (!is_resource($filePHP))
        return false;

    $sql_activity     = "SELECT id, name FROM user_type";
    $result_activity  = mysqli_query( $this->mysqli , $sql_activity  );

    fwrite($filePHP, "\n  \$user_types = array(");
    while($row = mysqli_fetch_array($result_activity))
    {
        if(!$initial)
        fwrite($filePHP, ",");

        fwrite($filePHP, "'".$row['id']."' => _('".$row['name']."')" );

        $initial = false;
    }
    fwrite($filePHP, "); \n");
    fclose($filePHP);
}

Then just use poEdit to translate and use $user_types array:

while($row = mysqli_fetch_array($result_user_type))
{
   echo "<option $selected value=\"".$row['id']."\">".$user_types[$row['id']]." </option>";
}  

I don't know if is it the best option but that options solves my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM