2013-03-06 63 views
0

所以即时通讯使这个网站必须有多种语言的工作。我探讨了一下,得出结论,我应该使用XML文件,每种语言一个。女巫对我来说很有意义,但这里是我的问题:PHP中的XML语言文件

我做了一个XML文件看起来像这样:

<?xml version="1.0" encoding="utf-8"?> 
<translations> 
    <frontpage> 
    <!--Main translation--> 
    <translation string="email" value="E-mail" /> 
    <translation string="password" value="Password" /> 
    <translation string="createacc" value="Create account" /> 
    <translation string="login" value="Login" /> 
    <!--Errors--> 
    <translation string="erroremail1" value="E-mail not valid" /> 
    <translation string="erroremail2" value="There's no account with that e-mail" /> 
    <translation string="errorpass" value="Incorrect password" /> 
    </frontpage> 
</translations> 

但我只是不明白怎么的XMLReader和DOM文档,从PHP库,作品。这是我的代码至今:

public function Translate($page,$string,$variables = array()) { 
    $reader = new XMLReader(); 
    $reader->open(www::findFile("lang/".$this->short.".xml")); 
    //Here i want to find the <translation> with the attribute string that is === $string 
    //With the parent of $page (fx. Translate("frontpage","erroremail1")) 
    $reader->close(); 

    $find = array(); 
    for ($x = 0; count($find) != count($variables); $x++) $find[] = "{".$x."}"; 
    return (isset($value)) ? str_replace($find,$variables,$value) : "NOT TRANSLATED (".$string.")"; 
} 

SOLUTION:

public function Translate($page,$string,$variables = array()) { 
    //Read from XML 
    $reader = simplexml_load_file(www::findFile("lang/".$this->short.".xml")); 
    foreach ($reader->$page->translation as $t) if ($t['string'] == $string) { $value = $t['value']; break; } 
    $find = array(); 
    for ($x = 0; count($find) != count($variables); $x++) $find[] = "{".$x."}"; 
    return (isset($value)) ? str_replace($find,$variables,$value) : "NOT TRANSLATED (".$string.")"; 
} 
+0

simplexml_load_file是更好的选择。 http://blog.teamtreehouse.com/how-to-parse-xml-with-php5 – 2013-03-06 08:46:20

+0

如果你不知道XMLReader或DOMDocument或SimpleXML的工作原理,那么你真的确定使用XML的决定是这样的吗?一个好主意 – 2013-03-06 09:01:23

+0

马克贝克,是的,我是。我宁愿用几天的时间学习这些东西,然后使用某种后门。 Sibiraj thx的链接,它真的有帮助 – CoBolt 2013-03-06 09:22:03

回答

0

如果编码语言以及里面的文件就可以了 - 但绝不能 - 把多语言相同的文件中。 XML确实支持两者。只是说,因为你选择了XML,这将是一个好处。

对于你的程序中,你只需要一个映射为

page + string + language:= translation 

正如你的操作,这是一种语言只有你甚至可以忽略它,所以你可以只取一个数组:

$translations[$string] 

每种语言和页面。所有你需要做的就是将你的文件转换成一个数组:

$getTranslations = function($file, $page) { 
    $translations = []; 
    foreach(simplexml_load_file($file)->$page->translation as $translation) 
    { 
     $translations[$translation['string']] = $translation['value']; 
    } 
    return $translations;   
} 

$translations = $getTranslations($file, $page); 

if (isset($translations[$string]) { 
    // found 
} else { 
    // not found (e.g. fallback to $string) 
} 

这肯定会留下很多优化空间,你可以保留每个文件/页面在内存中的翻译,所以你只需要加载一次。或者您可以使用xpath()来获取该值。