這種跨網域技術的方式最大的優點在於~ 他只需要單方面的向你所想要請求的資源進行溝通即可~
也就是說,我們先前所曾介紹過的「跨網域請求(二) - Flash Plug-In」、「跨網域請求(一) - Cross-Domain Script Tag」都需要雙方遵循著某種條件才能達成進行溝通~
而最簡單的例子不外乎像是Flickr所提供的API~ 它就是採用「Cross-Domain Script Tag」來達成的~
不過利用「Cross Domain Proxy」最大的缺點就在於~ 你需要將所有請求的資源都交由這台「Proxy」委任地去幫你處理~ 這將會造成「IP」被對方的伺服器封鎖,或是負荷過載的情形發生~ 所以這時就需要「CSProxy」才能解決這些問題~ 這部份留待以後再介紹~
我們就直接來看一個簡單的「Corss Domain Proxy」的例子,此例子以「Google Translate」為例:
Translate.php
<?php require_once "HttpClient.php"; if($_POST) { $sentence = $_POST['input']; $uri = "http://translate.google.com/translate_t"; $data = array('langpair' => 'en|zh-TW', 'h1' => 'en', 'ie' => 'UTF8', 'text' => $sentence); $request = new HttpClient(); $request->setContent($data); $request->setUri($uri); $body = $request->doAction(); $regex = '/<div id=result_box dir=\"ltr\">(.*)<\/div><\/td>/Us'; preg_match($regex,$body,$match); echo $match[1]; } ?>
HttpClient.php
此程式參考HTTP POST from PHP, without cURL,您可以自行修改並擴充~ 當然也歡迎您再分享您的成果 ^^
<?php /** * Date: 2008/04/17 * Shen(http://blog.ring.idv.tw) */ class HttpClient { private $uri; private $params; function __construct() { $this->params = array ( 'http' => array ( 'method' => 'POST', 'content' => '', ) ); } public function setUri($uri) { $this->uri = $uri; } public function setContent($content) { $this->params['http']['content'] = http_build_query($content); } public function doAction() { $ctx = stream_context_create($this->params); $fp = @fopen($this->uri, 'rb', false, $ctx); if(!$fp) throw new Exception("Problem: $php_errormsg"); $response = @stream_get_contents($fp); if ($response === false) throw new Exception("Problem: $php_errormsg"); return $response; } } ?>