Google Suggestion Engine no Flex

   

Bem, que não é um bom titulo para um post eu sei, mas foi o que se arranjou.

Desta feita, depois de ver um post no  (http://www.aboutflex.net) onde o autor apresentava uma class para AIR ( http://www.aboutflex.net/flex/flex-class-that-asks-google-for-suggestions/ ) que trabalhava com o motor de sugestões do google para buscar as palavras e sugestões ao google, como achei bem interessante decidi então tentar passar pela restrição do sandbox do flash, que não permite acesso a conteudo de outros sites que não do próprio servidor (possivel apenas com um crossdomain.xml, que o google não gosta), que resultou num script bem simples (no seu final, que os testes foram inumeros) que permite servir de gateway para esse serviço do google.

Vejam o simples código:

Download: send.php
<?php
 
$host="http://www.google.com";
 
$text=$_GET['q'];
 
$len=$_GET['cp'];
 
 
$text=str_replace(" ","%20",$text);
 
 
$instruction="/complete/search?hl=en&client=suggest&js=true&q=".$text."&cp=".$len;
 
$url=$host.$instruction;
 
 
if ((double)phpversion() >= 4.2)
    
{
        
ini_set('allow_url_fopen', '1');
    
}
 
 
$s = @file_get_contents($url);
    
if (empty($s))
    
{
        
echo "";
    
}
    
else
    
{
    
echo $s;
    
}
?>
Download: send.php

Simples não?

A nivel do Flex, obtemos as sugestões apenas com a seguinte class:

Download: gsug.as
/**EN: Implementation of google sugestions class for AIR from
 *
http://www.aboutflex.net/flex/flex-class-that-asks-google-for-suggestions/
 *
 * PT: Implementação da class google sugestions para AIR de
 *
http://www.aboutflex.net/flex/flex-class-that-asks-google-for-suggestions/
 *
 *
http://www.msdevstudio.com
 *
 * The send.php sould be placed on the same path of main .swf file
 * */

 
 
package com.msdevstudio
{
    
import flash.display.Sprite;
    
import flash.events.Event;
    
import flash.events.EventDispatcher;
    
    
import mx.collections.ArrayCollection;
    
import mx.rpc.events.ResultEvent;
    
import mx.rpc.http.HTTPService;
 
    
[Event(name="suggested", type="flash.events.Event")]
    
    
public class gsug extends Sprite
    
{
        
public const SUGGESTED:String='suggested'
        
private var _dataProvider:ArrayCollection=new ArrayCollection();
        
        
public function gsug()
        
{
        
}
        
        
public function findSuggests(string:String):void{
            
var hs:HTTPService=new HTTPService();
            
/*use our server-side script send.php to get suggestions*/           
            
            
hs.url="send.php?q="+string+"&cp="+string.length;
            
            
hs.addEventListener(ResultEvent.RESULT,parseResults)
                        
            
hs.send()
        
}
 
        
protected function parseResults(e:ResultEvent):void{
            
            
var tmp:Array=e.result.split('new Array')[1].split(', "');
            
_dataProvider=new ArrayCollection();
            
for (var i:int=1;i<tmp.length-1;i+=2){
 
                
tmp[i]=tmp[i].replace('"',"");
                
tmp[i]=tmp[i].replace('\\x27',"'");
                
_dataProvider.addItem(tmp[i]);
 
            
}
            
dispatchEvent(new Event('suggested'));
        
}
 
        
public function get dataProvider():ArrayCollection{
            
return _dataProvider;
        
}
 
    
}
}
Download: gsug.as

Podem ver o exemplo a funcionar aqui com o código fonte disponivel

Para usar em aplicações AIR basta substituir:

hs.url=”send.php?q=”+string+”&cp=”+string.length;

por:

hs.url=”http://www.google.com/complete/search?hl=en&client=suggest&js=true&q=”+string+”&cp=”+string.length;

Talvez seja util em algumas aplicações!

Abraço.

versão pdf temporariamente indisponivel.
Deixe um comentário or Deixe um Trackback

3 Comentários

  1. Julho 22, 2008 às 12:30 pm | Permalink

    Hi Mario,
    using PHP as bridge is a great idea!!
    I’ll use it for my next example !!

  2. Julho 23, 2008 às 10:13 am | Permalink

    Hi,
    as I said, I’ve written a little application that use your bridge and the Adobe AutoComplete component;
    this is the link

    Let me know what is your impression

    Cheers,
    Fedele

  3. Julho 23, 2008 às 11:37 am | Permalink

    Hi, i left you a comment, but i repeat, now it really seems a professional and very usefull component! :)

    Cheers!

Deixe um comentário

O seu email nunca será publicado ou partilhado. Campos obrigatórios estão marcados com um *

*
*