Файл: inflect.php
Строк: 68
<?php
class YandexInflect{
private $format = 'json';
private $word = '';
private $result = array();
private $error = '';
private $url = 'http://export.yandex.ru/inflect.xml?name=';
public function __construct($word, $format = 'xml')
{
$this->word = trim($word);
$this->result = array_fill(0, 6, $word);
if (strlen($format) > 0) {
$this->format = $format;
}
}
public function getInflect()
{
if(mb_strlen($this->word) == 0) {
$this->error = 'Длинна слова должна быть больше 0';
return false;
}
$this->url.=urlencode($this->word);
if ($this->format != 'xml') {
$this->url.='&format='.$this->format;
}
$this->getUrl($this->url);
return $this->result;
}
private function getUrl($url) {
$ch = @curl_init($url);
if (!$ch) {
$this->error = 'Невозможно инициализировать CURL';
return;
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = @curl_exec($ch);
if (!$r) {
$this->error = 'Невозможно отправить запрос';
return;
}
@curl_close($ch);
$this->parseResult($r);
}
private function parseResult($result)
{
if (strlen($result) == 0)return;
if ($this->format == 'xml') {
$xml = new DomDocument();
if (!$xml->loadXml($result))return;
$original = $xml->getElementsByTagName('original');
$inflection = $xml->getElementsByTagName('inflection');
if ($inflection->length > 1) {
for($i = 0; $i < $inflection->length; $i++) {
$this->result[$i] = $inflection->item($i)->nodeValue;
}
}
} else if($this->format == 'json') {
if (function_exists('json_decode')) {
$res = json_decode($result);
} else {
$res = self::jsonDecode($result);
}
if (count((array)$res) > 2) {
for ($i = 2; $i < count((array)$res); $i++) {
$this->result[($i-1)] = $res->$i;
}
}
} else {
$this->error = 'Неизвестный формат данных '.$this->format;
return;
}
}
private static function jsonDecode($code)
{
include_once 'JSON.php';
$json = new Services_JSON(SERVICES_JSON_IN_OBJ);
return $json->decode($code);
}
public function getError()
{
return $this->error;
}
}
?>