php - 需要使用google翻译API翻译xml文件内容

标签 php xml api google-translate

我需要知道如何使用Google翻译语言API使用PHP将XML文件的内容从英语翻译成另一种语言,XML文件中的数据如下所示:

<log>
    <titles>
        <logfile>Log File</logfile>
        <clearlog>Clear Log File</clearlog>
    </titles>
</log>  

所以我需要将文件传递给 Google API 并在其他特定语言(例如阿拉伯语)的标签之间返回新数据:

<log>
    <titles>
        <logfile>ملف اللوج</logfile>
        <clearlog>مسح محتويات الملف</clearlog>
    </titles>
</log>  

我希望一切都清楚..

谢谢

最佳答案

您可以使用GTranslate这是 Google Translate API 的包装器,可以简化您的工作。这是示例代码:

require_once ("include/GTranslate.php");

// original input xml
$orig_xml = "YOUR XML HERE";

// translate
$gt = new Gtranslate; // google translate object
$orig_text = array(); // original text
$trans_text = array(); // translated text

// extract text between tags
$split_tags_pattern = '|<[^>]+>([^<>]+)<\/[^>]+>|';
$tags = array();

preg_match_all($split_tags_pattern, $orig_xml, $tags, PREG_SET_ORDER);
/*
* preg_match_all returns:
*
* array() {
*   array () {
*       <xml tag>text</xml>,
*       text
*   },
*   ...
* }
*/

// translate each tag's inner text
foreach ($tags as $tag) {
    $text = trim($tag[1]);
    if ($text != '') {
        $orig_text[] = trim($tag[0]);
        $trans_text[] = str_replace($text, $gt->en_to_ar($text), $tag[0]); // en_to_ar method is used to translate from english to arabic.
    }
}

// replace original tag's inner text with translated ones
$trans_xml = str_replace($orig_text, $trans_text, $orig_xml);

请注意,Google 限制每个 IP 每天的 API 请求,因此对于包含许多标签的大型 XML,这可能不起作用,或者您可以将整个 XML(带标签)传递给 Google Translate(有 100000 个字符的限制)这也是,但这对于很多事情来说已经足够了),然后从翻译结果中提取翻译后的内部文本。

关于php - 需要使用google翻译API翻译xml文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8335424/

相关文章:

javascript - 如何在php中获取并打印页面内的图像

java - java.beans.XMLEncoder 的直接替代品

java - 错误:(41) Error parsing XML: not well-formed (invalid token) + cannot resolve the symbol R

java - HTTP Post 请求 Android

php - 通过 "google-api-php-client"库检索 Google 搜索分析

ios - Twitter iOS GET statuses/home_timeline 使用 Parse

php - php 和 MySQL 中三个文本框的最佳查询?

PHP Sendmail 发送的电子邮件内容在包含 CSS 内联样式时不显示

javascript - 在 XSLT 中获取 XML 元素

php - 为什么 php 4.3 中的 bcmath 比 php 5+ 快得多?