<?php namespace RSSAutopilot; /** * Class YandexTranslator * @package RSSAutopilot */ class YandexTranslator { private $apiKey; /** * Init YandexTranslator with API key * @param $apiKey */ public function __construct($apiKey) { $this->apiKey = $apiKey; } /** * Get list of supported translation directions * @param int $itemPerPage * @return array */ public function getLanguages($ui='en') { $languages = array(); if (!$this->apiKey) return $languages; $url = 'https://translate.yandex.net/api/v1.5/tr.json/getLangs?key='.$this->apiKey.'&ui='.$ui; $contents = wp_remote_get($url); if (!is_wp_error($contents)) { $list = json_decode($contents['body'], true); foreach ($list['dirs'] as $dir) { $parts = explode('-', $dir); $languages[$dir] = $list['langs'][$parts[0]] .' - '.$list['langs'][$parts[1]]; } } return $languages; } /** * Translate given text to specified language and format * @param $text * @param $lang * @param $format * @return string translated text */ public function translate($text, $lang, $format='text') { // ToDo: In order to prevent browser from converting &amp; to & // According to: http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2. $newText = $text; $params = array( 'key' => $this->apiKey, 'text' => $text, 'lang' => $lang, 'format' => $format ); $url = 'https://translate.yandex.net/api/v1.5/tr.json/translate'; $contents = wp_remote_post($url, array( 'body' => $params )); if (!is_wp_error($contents)) { $data = json_decode($contents['body'], true); if ($data['code'] == '200') { return html_entity_decode($data['text'][0]); } else { return $text; } } } } ?>