buildSuggestUrl($keyword); $data = $this->getRawSuggest($url); if ($data) { // // This parsing code could probably be a lot simpler if we used regex, // but that's not my strong point, so just do a bruteforce parse here. // $data = strstr($data, 'new Array('); if ($data === FALSE) return $items; // // Trim off the 'new Array(' // $data = substr($data, strlen('new Array(')); $i = strpos($data, ')'); if ($i === FALSE) return $items; $tmp = substr($data, 0, $i - 1); $tmp = str_replace('"', "", $tmp); $keys = explode(",", $tmp); // // skip to next array // TODO: this should be refactored... similar to code above // $data = strstr($data, 'new Array('); if ($data === FALSE) return $items; $data = substr($data, strlen('new Array(')); $i = strpos($data, ')'); if ($i === FALSE) return $items; $tmp = substr($data, 0, $i - 1); $values = explode('",', $tmp); $values = array_map("stripQuotes", $values); if (count($keys) == count($values)) { $items = $this->safeArrayCombine($keys, $values); } } return $items; } //-------------------------------------------------------------------------- function buildSuggestUrl($keyword) { return "http://www.google.com/complete/search?hl=en&js=true&qu=" . urlencode($keyword); } //-------------------------------------------------------------------------- // // Grab the raw data from Google Suggest. Uses curl, but could easily be mod'ed // to use another method, raw sockets, etc. // function getRawSuggest($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $data = curl_exec($ch); curl_close($ch); if (!($data === FALSE)) { return $data; } else { return false; } } //-------------------------------------------------------------------------- // // From public domain comment found on php.net: // http://www.php.net/manual/en/function.array-combine.php // by m71 at free dot net, 22-Oct-2004, 06:39 // function safeArrayCombine($a, $b) { if (count($a)!=count($b)) return FALSE; foreach($a as $key) list(,$c[$key])=each($b); return $c; } //-------------------------------------------------------------------------- } //------------------------------------------------------------------------------ // // Callback used to strip quotes from an array // function stripQuotes($item) { return str_replace('"', "", $item); } //------------------------------------------------------------------------------