09-01-2008, 07:54 PM
|
#3 (permalink)
|
|
The Prestige
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
|
Dunno if this will be of any use, but i have quickly botched a class to translate words using Google Translate.
Its a bit of a mess but it works, it also uses CURL and PHP DOM XPath.
PHP Code:
<?php error_reporting(0); class translatorException extends Exception {} class translator { private $m_szLangPair; private $m_szText; const BASE_URL = 'http://translate.google.com/translate_t?langpair=';
private function throwException($szMessage) { throw new translatorException($szMessage); }
private function getHTML() { $pCurl = curl_init(self::BASE_URL . $this->m_szLangPair); curl_setopt($pCurl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($pCurl, CURLOPT_HEADER, 1); curl_setopt($pCurl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($pCurl, CURLOPT_TIMEOUT, 15); curl_setopt($pCurl, CURLOPT_POST, 1); curl_setopt($pCurl, CURLOPT_POSTFIELDS, 'text=' . $this->m_szText); $szHtml = curl_exec($pCurl); if($szError = curl_error($pCurl)) { curl_close ($pCurl); $this->throwException($szError); } return $szHtml; } public function __call($szCall, $aArgs) { preg_match('/^([a-z]{2})2([a-z]{2})$/i', $szCall, $aMatches) or $this->throwException('Malformed system call, [lang]2[lang] e.g. en2it (ENglish to ITalian)');
$this->m_szLangPair = urlencode($aMatches[1] . '|' . $aMatches[2]) . '&'; is_null($aArgs) || !is_array(reset($aArgs)) or $this->throwException('You have entered either a NULL or incompatable type into the system, please only pass in a string to be converted'); $this->m_szText = urlencode((string)reset($aArgs)); $pDoc = new DomDocument; $pDoc->loadHTML($this->getHTML()); $pXpath = new DOMXPath($pDoc); return $pXpath->query('//div[@id="result_box"]')->item(0)->nodeValue; } }
To use:
PHP Code:
try { $lang = new translator; header('Content-type: text/html; charset="utf-8"'); echo $lang->en2hi('hello'); } catch (Exception $e) { echo $e->getMessage(); }
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)
|
|
|
|