1. <?php
    mb_language('Japanese');
    mb_http_output("UTF-8");
    ob_start("mb_output_handler");
    include("proxy.php");
    // JSON形式で出力するときにこのファイルを利用する
    include("JSON.php");
    // proxyを利用する場合は$use_proxy = 1にする;
    $use_proxy = 0;
    // proxyを利用するhostとportを指定にする;
    $proxy_host = 'proxy.example.com';
    $proxy_port = 8080;
    $no_proxy = array(
        'localhost',        // localhost 
        '127.0.0.0/8',      // loopback
    );
    $TidyConfig = array('indent' => TRUE,
                    'output-xhtml' => TRUE,
                    'wrap' => 200);
    function getHTML($url){
        // URLの情報を取得し、データを戻す
        $rdata = http_request($url);
        $data = $rdata['data'];
        $data = mb_convert_encoding($data,"UTF-8", "auto");
        return ($data);
    }
    
    function _getParam(tidyNode $node, &$urls = NULL) { 
        $urls = (is_array($urls)) ? $urls : array(); 
        if(isset($node->id)) { 
            // Aタグだったら
            if($node->id == TIDY_TAG_A) {
                // Aタグ属性で spell=1となる部分を抜き出す
                if (strstr ($node->attribute['href'] ,"spell=1") !==FALSE){ 
                    // マッチすればそのnodeを配列に入れる
                    $urls[] = $node->value;
                }
            }
        }
        if($node->hasChildren()) { 
            foreach($node->child as $c) { 
                _getParam($c, $urls); 
            }
        }
        return $urls;
    }
    global $TidyConfig;
    if ($_GET['q']<>""){
        $kw = $_GET['q'];
        // 入力されたキーワードをURLエンコードしてGoogleで検索する際のURIを作成
        $req = "http://www.google.co.jp/search?source=ig&hl=ja&q=".urlencode($kw);
        // 作成したURIにアクセスする
        $data = getHTML($req);
        // tidyオブジェクト作成
        $tidy = tidy_parse_string($data, $TidyConfig,"utf8");
        $tidy->cleanRepair();
        // tidyでチェックする
        $res = _getParam($tidy->body());
        $obj = array();
        if(count($res)>0){
            // 「もしかして」といわれたら
            // $resを分解してもしかしての部分だけ無理矢理抽出する
            $res_ = explode('class=p>',$res[0]);
            if (count($res_)<2){
                $res_ = explode('class="p">',$res[0]);
            }
            $res__ = explode("</a>",$res_[1]);
            $rs = str_replace("<b>","",$res__[0]);
            $rs = str_replace("</b>","",$rs);
            $rs = str_replace("<i>","",$rs);
            $rs = str_replace("</i>","",$rs);
            // 配列に入れる
            array_push($obj,array("word"=>$kw,"res"=>$rs));
        }else{
            // 「もしかして」といわれなければ
            array_push($obj,array("word"=>$kw,"res"=>$kw));
        }
        // JSONオブジェクト作成
        $json = new Services_JSON();
        $js = $json->encode($obj);
        if ($_GET['callback']<>""){
            $src = $_GET['callback']."(";
            $src .= $js;
            $src .=");";
            // JSON形式で返す。
            echo $src;
        }
    }
    ob_end_flush();
    ?>