Oct 3

Yahoo API Code

Posted by Jaimie Sirovich on Oct. 3rd, 2006. 0 comments — voice your opinion.

BECOME AN EGGHEAD. SUBSCRIBE TO OUR RSS FEED OR FOLLOW US ON TWITTER!

Learn to be as nerdy as we are by never missing our latest blog entries. Receive great tips, tricks, and ideas on improving your web site every day! Subscribe via our RSS Feed, follow us, or use the chicklets in the sidebar for more options.
X

<?php

/* sample usage:
$tree = new xmlTreeParser('sample.xml');
echo '<pre>';
print_r($tree->getTree());
*/

class xmlTreeParser {

    var $_parser;
    var 
$_xmldata;
    var 
$_obj;
    var 
$_xmltree;
    var 
$_encoding;

    function xmlTreeParser($filename='',$data='',$encoding '')
    {
        
$this->_init();
        if (
$filename)
            
$this->xmlFromFile($filename);
        else if (
$data)
            
$this->xmlFromData($data);
        
$this->_encoding $encoding;    
    }
    
    function 
_init()
    {
        
$this->_parser xml_parser_create($this->_encoding);
        
$this->_obj->tree '$this->_obj->xml';
        
$this->_obj->xml '';
        
        
xml_set_object($this->_parser$this);
        
xml_set_element_handler($this->_parser"startElement""endElement");
        
xml_set_character_data_handler($this->_parser"characterData");
        
xml_parser_set_option($this->_parserXML_OPTION_CASE_FOLDINGfalse);
    }
    
    function 
xmlFromFile($filename)
    {
        
$this->_xmldata implode('',file($filename));
        return 
$this->_parse();
    }
    
    function 
xmlFromData($data)
    {
        
$this->_xmldata $data;
        return 
$this->_parse();
    }
    
    function 
_parse()
    {
        
xml_parse($this->_parser$this->_xmldata);
    
        
$this->_xmltree $this->_flatten($this->_obj->xml);
    
        
// reset for next run
        
xml_parser_free($this->_parser);
        
$this->_init();
    
        return 
$this->_xmltree;
    }
    
    function 
_flatten($tree)
    {
        if (
is_object($tree))
            
$vars array_keys(get_object_vars($tree));
        else if (
is_array($tree))
            
$vars array_keys($tree);
        else
            
$vars = Array();
    
        
$ct count($vars);
    
        if (
$ct == && $vars[0] == 'data')
            return 
$tree->data;
    
        foreach (
$vars as $key) {
            if (
is_object($tree))
            
$tree->{$key} = $this->_flatten($tree->{$key});
            else if (
is_array($tree))
            
$tree[$key] = $this->_flatten($tree[$key]);
        }
    
        return 
$tree;
    }
    
    function 
startElement($parser$name$attrs)
    {
        
// If var already defined, make array
        
eval('$test=isset('.$this->_obj->tree.'->'.$name.');');
        if (
$test) {
            eval(
'$tmp='.$this->_obj->tree.'->'.$name.';');
            eval(
'$arr=is_array('.$this->_obj->tree.'->'.$name.');');
            if (!
$arr) {
                eval(
'unset('.$this->_obj->tree.'->'.$name.');');
                eval(
$this->_obj->tree.'->'.$name.'[0]=$tmp;');
                
$cnt 1;
            }    else {
                eval(
'$cnt=count('.$this->_obj->tree.'->'.$name.');');
            }
    
            
$this->_obj->tree .= '->'.$name."[$cnt]";
        } else {
            
$this->_obj->tree .= '->'.$name;
        }
    
        if (
count($attrs)) {
            eval(
$this->_obj->tree.'->attr=$attrs;');
        }
    }
    
    function 
endElement($parser$name)
    {
        
// Strip off last ->
        
for($a=strlen($this->_obj->tree);$a>0;$a--) {
            if (
substr($this->_obj->tree$a2) == '->') {
                
$this->_obj->tree substr($this->_obj->tree0$a);
                break;
            }
        }
    }

    function _escapePHPSingleQuotedString($string)
    {
        return 
preg_replace('#([\'\])#''\1'$string);        
    }            
    
    function 
characterData($parser$data)
    {
        
$data $this->_escapePHPSingleQuotedString($data);
            
        if (
$data !== '')
            eval(
$this->_obj->tree.'->data.=\''.$data.'\';');
    }
    
    function 
getTree()
    {
        return 
$this->_xmltree;
    }
}

?> <?

// +----------------------------------------------------------------------+
// | YahooAPI                                                             |
// | Uses Yahoo REST API to obtain search results                         |
// +----------------------------------------------------------------------+
// | Copyright (c) 2004 Jaimie Sirovich                                   |
// +----------------------------------------------------------------------+
// | Author: Jaimie Sirovich <jsirovic@gmail.com>                         |
// +----------------------------------------------------------------------+

class YahooAPI
{
    
    var 
$_parameters;
    
    function 
YahooAPI($app_id)
    {        
        
$_parameters = array();
        
        
$this->setParameter('appid'$app_id);
    }
    
    function 
setParameter($key$value)
    {
        
$this->_parameters[$key] = $value;
    }
    
    function 
simpleQuery($query_string$limit ''$offset '')
    {
        
$this->setParameter('query'$query_string);
        if (
$limit)     $this->setParameter('results'$limit);            
        if (
$offset$this->setParameter('start'$offset);        
        return 
$this->executeQuery();
    }
    
    function 
spellCheckQuery($query_string)
    {
        
$this->setParameter('query'$query_string);
        
$xml_parser = new xmlTreeParser(''$this->_executeQuery('spellingSuggestion'));        
        
$tmp $xml_parser->getTree();
        return 
$tmp->ResultSet->Result;
    }

    function imageQuery($query_string)
    {
        
$this->setParameter('query'$query_string);
        if (
$limit)     $this->setParameter('results'$limit);            
        if (
$offset$this->setParameter('start'$offset);        
        return 
$this->executeImageQuery('imageSearch');
    }    

    function newsQuery($query_string$limit ''$offset '')
    {
        
$this->setParameter('query'$query_string);
        if (
$limit)     $this->setParameter('results'$limit);            
        if (
$offset$this->setParameter('start'$offset);        
        return 
$this->executeNewsQuery('newsSearch');
    }        
    
    function 
_executeNewsQuery($service_name)
    {
        
$url "http://api.search.yahoo.com/NewsSearchService/V1/$service_name";
        
        
$params $this->_parameters;
        
        foreach (
$params as $index => $p) {
            
$params[$index] = "$index=" urlencode($p);
        }
        
        
$param_str implode('&'$params);

        $full_url $url '?' $param_str;
        
        
//echo $full_url;
        
        
$ch curl_init();
        
curl_setopt($chCURLOPT_URL,$full_url);
        
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
        
        
$result curl_exec($ch);
        
        
//echo htmlentities($result);
        
        
curl_close($ch);

        return $result;    
    }        
    
    function 
_executeImageQuery($service_name)
    {
        
$url "http://api.search.yahoo.com/ImageSearchService/V1/$service_name";
        
        
$params $this->_parameters;
        
        foreach (
$params as $index => $p) {
            
$params[$index] = "$index=" urlencode($p);
        }
        
        
$param_str implode('&'$params);

        $full_url $url '?' $param_str;
        
        
$ch curl_init();
        
curl_setopt($chCURLOPT_URL,$full_url);
        
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
        
        
$result curl_exec($ch);
        
curl_close($ch);

        return $result;    
    }    
    
    function 
_executeQuery($service_name)
    {
        
$url "http://api.search.yahoo.com/WebSearchService/V1/$service_name";
        
        
$params $this->_parameters;
        
        foreach (
$params as $index => $p) {
            
$params[$index] = "$index=" urlencode($p);
        }
        
        
$param_str implode('&'$params);
        
        
$ch curl_init();
        
curl_setopt($chCURLOPT_POST,1);
        
curl_setopt($chCURLOPT_POSTFIELDS,$param_str);
        
curl_setopt($chCURLOPT_URL,$url);
        
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
        
        
$result curl_exec($ch);
        
curl_close($ch);
        
        return 
$result;    
    }
    
    function 
executeNewsQuery($service_name 'newsSearch')
    {
        return 
$this->_parseXML($this->_executeNewsQuery($service_name));
    }    
    
    function 
executeImageQuery($service_name 'imageSearch')
    {    
           return 
$this->_parseXML($this->_executeImageQuery($service_name));
    }    
    
    function 
executeQuery($service_name 'webSearch')
    {    
           return 
$this->_parseXML($this->_executeQuery($service_name));
    }
        
    function 
_arrayizeVar($var$nulls_to_empty_arrays false)
    {
        if (!
is_array($var)) {
            
            if (
$var === null && $nulls_to_empty_arrays) {
                return array();
            } else {
                return array(
$var);    
            }
            
        } else {
            return 
$var;    
        }
    }    
    
    function 
_parseXML($xml)
    {
        
        
$xml_parser = new xmlTreeParser(''$xml);
        
        
$tmp $xml_parser->getTree();
        
        
//print_ar($tmp);
        
        
$result_array = array();
        
        
$result_array['total_results'] = $tmp->ResultSet->attr['totalResultsAvailable'];
        
        
$results_tmp = array();
        
        if (
$tmp->ResultSet->Result) foreach ($this->_arrayizeVar($tmp->ResultSet->Result) as $result) {
            
            
$results_tmp[] = array('title' => $result->Title'description' => $result->Summary'url' => $result->Url'summary' => $result->Summary'date_reported' => $result->PublishDate);
            
        }
        
        
$result_array['results'] = $results_tmp;
        
        return 
$result_array;
        
    }

    function makeURL($query_string$limit ''$offset ''$additional_parameters '')
    {
        
$url 'http://search.yahoo.com/search?';
        
        
$params = array();

        $params['p'] = $query_string;        
        
$params['n'] = $limit;
        
$params['b'] = $offset;
        
        if (
$additional_parameters)
            
$params array_merge($params$additional_parameters);
        
        foreach (
$params as $index => $p) {
            
$params[$index] = "$index=" urlencode($p);
        }
        
        
$param_str implode('&'$params);
        
        return 
$url $param_str;
    }    
    
}

?>

Tell an amigo:
  • Sphinn
  • Digg
  • Reddit
  • del.icio.us
  • StumbleUpon
  • Facebook




Care To Bang On The Keys ... ?