简体   繁体   English

翻译网站的简单方法

[英]Easy way to translate a website

Question问题

I have a fairly static website with just a few basic PHP usage.我有一个相当静态的网站,只有一些基本的 PHP 用法。 Now the customer would like to have this website translated.现在客户想要翻译这个网站。 I do have a solution, but it's cumbersome and I was wondering how others are doing it and what is the standard (in frameworks, etc.).确实有一个解决方案,但它很麻烦,我想知道其他人是如何做的以及标准是什么(在框架等中)。

My Way我的方式

My way (I have simplified it a bit for the sake of easier understanding): I generate a PHP array for each language from the database and store this array in a language file, like es.php for Spanish.我的方式(为了更容易理解,我已经简化了一点):我从数据库中为每种语言生成一个 PHP 数组,并将这个数组存储在一个语言文件中,比如西班牙语的 es.php。

I then translate a string in HTML using a tr function like this:然后我使用 tr 函数翻译 HTML 中的字符串,如下所示:
Before: <h1>Hello World</h1>之前: <h1>Hello World</h1>
After: <h1><?php echo tr('Hello World'); ?></h1>之后: <h1><?php echo tr('Hello World'); ?></h1> <h1><?php echo tr('Hello World'); ?></h1> which gives <h1>Hola Mundo</h1> for Spanish. <h1><?php echo tr('Hello World'); ?></h1> <h1>Hola Mundo</h1>为西班牙语提供<h1>Hola Mundo</h1>

The Problem问题

This is cumbersome and error prone.这很麻烦且容易出错。 I have to go through each .php file and replace all the hardcoded strings with this PHP tag with echo.我必须遍历每个 .php 文件,并用这个带有 echo 的 PHP 标记替换所有硬编码的字符串。
Is there a better way?有没有更好的办法? How are others doing it?其他人是怎么做的? If needed, I can elaborate on my implementation.如果需要,我可以详细说明我的实现。

You should look into the PHP GETTEXT extension, it is very fast and will scan your PHP files for strings to translate with .MO and .PO files您应该查看 PHP GETTEXT 扩展名,它非常快,并且会扫描您的 PHP 文件中的字符串以使用 .MO 和 .PO 文件进行翻译

You then can simply do something like __('Hello World');然后,您可以简单地执行类似__('Hello World'); or if you already have all the strings with tr('Hello World');或者如果您已经拥有tr('Hello World');所有字符串tr('Hello World'); then you could just modify the tr function to pass it through __(string) or gettext(string) like..那么您可以修改tr函数以通过__(string)gettext(string)传递它,例如..

function tr($string){
    __($string)
}

You could always punt and translate your site using Google's Tools and Resources .您始终可以使用 Google 的工具和资源 对您的网站进行定位和翻译。

Generally, I consider a multilingual site no longer to be "static".一般来说,我认为多语言网站不再是“静态的”。 I use Drupal to implement sites.我使用Drupal来实现站点。 It has some excellent internationalization options .它有一些优秀的国际化选项

A little late for you, I suppose but in case someone like me stumbles across this thread... Because I currently have the same problem you do.我想对你来说有点晚了,但如果像我这样的人偶然发现了这个线程......因为我目前遇到了与你相同的问题。 Unfortunately, there doesn't appear to be a "non-cumbersome way" to do this with PHP.不幸的是,似乎没有一种“不麻烦的方法”可以用 PHP 来做到这一点。 Everything seems to involve lots of function-calls (if you have a lot of text).一切似乎都涉及大量的函数调用(如果你有很多文本)。

Well... there is ONE convenient way.嗯...有一种方便的方法。 Not exactly safe though.虽然不完全安全。 Manipulating the output buffer before it's sent to the user: => http://dev-tips.com/featured/output-buffering-for-web-developers-a-beginners-guide在发送给用户之前操​​作输出缓冲区:=> http://dev-tips.com/featured/output-buffering-for-web-developers-a-beginners-guide

So you could depending on the language chosen just define an array filled with "from->to"-data and replace all the readable text in your buffer by looping through that.因此,您可以根据选择的语言定义一个填充“from->to”-data 的数组,并通过循环替换缓冲区中的所有可读文本。

But of course... if you eg replace "send" (English) with "senden" (German) and you link to a "send.html", it would break that link.但是当然...如果你例如用“send”(德语)替换“send”(英语)并且你链接到“send.html”,它会破坏那个链接。

So if one has to translate not only long, definitely unique strings but also shorter ones, one would have to manipulate only the text that is readable to the user.因此,如果不仅要翻译长的、绝对唯一的字符串,还要翻译较短的字符串,则必须只处理用户可读的文本。 There is a solution for that too - however, that is JavaScript based: => http://www.isogenicengine.com/documentation/jquery-multi-language-site-plugin/也有一个解决方案 - 但是,这是基于 JavaScript 的:=> http://www.isogenicengine.com/documentation/jquery-multi-language-site-plugin/

Do way i translate my website is Under doctype have lang then your selected lang, eg below,我翻译我的网站的方式是在文档类型下有 lang 然后是你选择的 lang,例如下面,

Then create a php function to get this by $_POST['get'], and have have that function load up the selected language file/db etc,然后创建一个 php 函数以通过 $_POST['get'] 获取它,并让该函数加载选定的语言文件/db 等,

Try this solution.试试这个解决方案。 It works for me.这个对我有用。 It has french and english translation.它有法语和英语翻译。

Index.php索引.php

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>How to Translate your Site in Runtime using Jquery - demo</title>
<link rel="stylesheet" href="css/main.css" type="text/css" />
<script src="js/jquery.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="example">
<h3><a href="#">How to Translate your Site in Runtime using Jquery - demo</a></h3>
<div id="content">
<div class="lang_switcher">
<button id="en" class="lang">EN</button>
<button id="fr" class="lang">FR</button>
</div>
<div style="clear:both;"></div>
<!-- nav menu start -->
<ul id="nav">
<li><a href="#nogo" key="home" class="tr">Home</a></li>
<li><a href="#nogo" key="peoples" class="tr">Peoples >></a>
<ul>
<li><a href="#nogo" key="all_list" class="tr">All list</a></li>
<li><a href="#nogo" key="online" class="tr">Online</a></li>
</ul>
</li>
<li><a href="#nogo" key="articles" class="tr">Articles >></a>
<ul>
<li><a href="#nogo" key="js" class="tr">JavaScript</a></li>
<li><a href="#nogo" key="php" class="tr">PHP</a></li>
<li><a href="#nogo" key="html" class="tr">HTML</a></li>
<li><a href="#nogo" key="css" class="tr">CSS</a></li>
</ul>
</li>
<li><a href="#nogo" key="contact_us" class="tr">Contact us</a></li>
</ul>
<!-- nav menu end -->
<div style="clear:both;"></div>
<h2 key="welcome" class="tr">Welcome guests</h2>
<hr />
<div key="a_man" class="tr">A man bribes a rabbit with wicked dentures to run away with him in a sailboat via an ambulance. Bribing Koalas to remain illegally in one place. Trees anchor me in place. / Your mom drives the ambulance, but the city is farther than it appears.</div>
</div>
</div>
</body>
</html>

main.js主文件

// preparing language file
var aLangKeys=new Array();
aLangKeys['en']=new Array();
aLangKeys['fr']=new Array();
aLangKeys['en']['home']='Home';
aLangKeys['en']['peoples']='Peoples >>';
aLangKeys['en']['all_list']='All list';
aLangKeys['en']['online']='Online';
aLangKeys['en']['articles']='Articles >>';
aLangKeys['en']['js']='JavaScript';
aLangKeys['en']['php']='PHP';
aLangKeys['en']['html']='HTML';
aLangKeys['en']['css']='CSS';
aLangKeys['en']['contact_us']='Contact us';
aLangKeys['en']['welcome']='Welcome guests';
aLangKeys['en']['a_man']='A man bribes a rabbit with wicked dentures to run away with him in a sailboat via an ambulance. Bribing Koalas to remain illegally in one place. Trees anchor me in place. / Your mom drives the ambulance, but the city is farther than it appears.';

aLangKeys['fr']['home']='Accueil';
aLangKeys['fr']['peoples']='Peuples >>';
aLangKeys['fr']['all_list']='Toutes les listes';
aLangKeys['fr']['online']='En ligne';
aLangKeys['fr']['articles']='Articles >>';
aLangKeys['fr']['js']='JavaScript';
aLangKeys['fr']['php']='Php';
aLangKeys['fr']['html']='Html';
aLangKeys['fr']['css']='Css';
aLangKeys['fr']['contact_us']='Contactez nous';
aLangKeys['fr']['welcome']='Bienvenue aux invites';
aLangKeys['fr']['a_man']="Un homme soudoie un lapin avec des prothèses méchantes pour s'enfuir avec lui dans un voilier via une ambulance. Corruption des Koalas pour qu'ils restent illégalement à un endroit. Les arbres m'ancrent en place. / Votre mère conduit l'ambulance, mais la ville est plus loin qu'il n'y paraît.";
$(document).ready(function() {
// onclick behavior
$('.lang').click( function() {
var lang = $(this).attr('id'); // obtain language id
// translate all translatable elements
$('.tr').each(function(i){
$(this).text(aLangKeys[lang][ $(this).attr('key') ]);
});
} );
});

And some css- main.css还有一些 css-main.css

body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.example{background:#FFF;width:500px;height:500px;font-size:80%;border:1px #000 solid;margin:0.5em 10% 0.5em;padding:1em 2em 2em;-moz-border-radius:3px;-webkit-border-radius:3px}
.lang_switcher{float:right;overflow:hidden;}
/* nav menu styles */
#nav,#nav ul{list-style:none;font:10px verdana, sans-serif;border:1px solid #000;background:#fff;position:relative;z-index:200;border-color:#eca #b97 #a86 #edb;border-width:1px 2px 2px 1px;margin:0;padding:0 0 5px}
#nav{height:25px;padding:0}
#nav table{border-collapse:collapse}
#nav li{float:left;padding:0 20px 0 10px}
#nav li li{float:none}
#nav li a li{float:left}
#nav li a{display:block;float:left;color:#888;height:25px;padding-right:5px;line-height:25px;text-decoration:none;white-space:nowrap}
#nav li li a{height:20px;line-height:20px;float:none}
#nav li:hover{position:relative;z-index:300;background:#fff}
#nav a:hover{position:relative;z-index:300;text-decoration:underline;color:#b75}
#nav :hover ul{left:0;top:22px}
#nav a:hover ul{left:-10px}
#nav li:hover li:hover > ul{left:-15px;margin-left:100%;top:-1px}
#nav li:hover > ul ul{position:absolute;left:-9999px;top:-9999px;width:auto}
#nav li:hover > a{text-decoration:underline;color:#b75}
#nav a:hover a:hover ul,#nav a:hover a:hover a:hover ul,#nav a:hover a:hover a:hover a:hover ul,#nav a:hover a:hover a:hover a:hover a:hover ul{left:100%;top:-1px}
#nav ul,#nav a:hover ul ul,#nav a:hover a:hover ul ul,#nav a:hover a:hover a:hover ul ul,#nav a:hover a:hover a:hover a:hover ul ul{position:absolute;left:-9999px;top:-9999px}

I made a class to do mine我做了一个课程来做我的

class WILang

{ {

    function __construct() 
{
     $this->WIdb = WIdb::getInstance();

}

public static function all($jsonEncode = true) {
    // determine lanuage
    $language = self::getLanguage();
    //echo $language;

    $WIdb = WIdb::getInstance();
        //$file = WILang::getFile($language);
        //echo $file;
        //echo $language;
    if ( ! self::isValidLanguage($language) )
    die('Language file doesn\'t exist!');
    else {

        $sql = "SELECT * FROM `wi_trans` WHERE `lang` = :file";
        $query = $WIdb->prepare($sql);
        $query->bindParam(':file', $language, PDO::PARAM_STR);
        $query->execute();
        //$result = array();
        while ($result = $query->fetchAll(PDO::FETCH_ASSOC)) {
            echo "{";
            foreach ($result as $res) {
            echo '"' .$res['keyword'] .'":"' . $res['translation'] . '",';
             //return array($res['keyword'] => $res['translation'] ,);  
        }

        echo "}";
        }

        }
}

public static function get($key ) //, $bindings = array()
{
    // determine language
    $language = self::getLanguage();

    $WIdb = WIdb::getInstance();

    $sql = "SELECT * FROM `wi_trans` WHERE `keyword`=:key AND lang=:lang";
    $query = $WIdb->prepare($sql);
    $query->bindParam(':key', $key, PDO::PARAM_STR);
    $query->bindParam(':lang', $language, PDO::PARAM_STR);
    $query->execute();

    $res = $query->fetch(PDO::FETCH_ASSOC);
    if($res > 0)
        return $res['translation'];
    else
        return '';
}

 public static function setLanguage($language) 
 {

    // check if language is valid
    if ( self::isValidLanguage($language) ) {
        //set language cookie to 1 year
        setcookie('wi_lang', $language, time() + 60 * 60 * 24 * 365, '/');

        // update session
        WISession::set('wi_lang', $language);

        //refresh the page
        header('Location: ' . $_SERVER['PHP_SELF']);
    }
}

     public static function getLanguage() 
     {
    // check if cookie exist and language value in cookie is valid
    if ( isset ( $_COOKIE['wi_lang'] ) && self::isValidLanguage ( $_COOKIE['wi_lang'] ) )
        return $_COOKIE['wi_lang']; // return lang from cookie
    else
        return WISession::get('wi_lang', DEFAULT_LANGUAGE);
}


    private static function getTrans($language) 
    {
        $WIdb = WIdb::getInstance();
        //$file = WILang::getFile($language);
        //echo $file;
        //echo $language;
    if ( ! self::isValidLanguage($language) )
    die('Language file doesn\'t exist!');
    else {
        //$language = include $file;
        //return $language;

        $sql = "SELECT * FROM `wi_trans` WHERE `lang` = :file";
        $query = $WIdb->prepare($sql);
        $query->bindParam(':file', $language, PDO::PARAM_STR);
        $query->execute();
        //$result = array();
        while ($result = $query->fetchAll(PDO::FETCH_ASSOC)) {
            echo "{";
            foreach ($result as $res) {
            echo '"' .$res['keyword'] .'":"' . $res['translation'] . '",';
             //return array($res['keyword'] => $res['translation'] ,);  
        }

        echo "}";
        }

        }

}



 private static  function getFile($language) 
 {
    $WIdb = WIdb::getInstance();
    $sql = "SELECT * FROM `wi_lang` WHERE `lang` = :file";
    $query = $WIdb->prepare($sql);
    $query->bindParam(':file', $language, PDO::PARAM_STR);
    $query->execute();

    $res = $query->fetch(PDO::FETCH_ASSOC);
    //echo $res['lang'];
    if ($res > 0)
        return $res['lang'];
    else
        return '';


}

    private static function isValidLanguage($lang) 
    {
    $file = self::getFile($lang);
    //echo $file;

    if($file == "")
    //if ( ! file_exists( $file ) )
        return false;
    else
        return true;
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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