I constructed a very simple PHP script for using Yahoo’s Search API a while ago. Partial credit goes to Sitepoint for the XML parser. I also wrote my own PHP5 version too (which I’ll add soon).

The Source Code

#Yahoo PHP API – Version 0.1 – The Bo$$, April 17th, 2005
#Remember that this is still in Beta, and may change
#Essentially I copied the code from a Sitepoint article on XML parsing, tweaked it, and added stuff
$insideitem = false;
$tag = ”;
$title = ”;
$description = ”;
$link = ”;
function startElement($parser, $name, $attrs) {
global $insideitem, $tag, $title, $description, $link;
if ($insideitem) {
$tag = $name;
} elseif ($name == ‘RESULT’) {
$insideitem = true;
}
}
function endElement($parser, $name) {
global $insideitem, $tag, $title, $description, $link;
if ($name == ‘RESULT’) {
printf(“%s“,
trim($link),htmlspecialchars(trim($title)));
printf(“%s”,htmlspecialchars(trim($description)));
$title = ”;
$description = ”;
$link = ”;
$insideitem = false;
}
}
function characterData($parser, $data) {
global $insideitem, $tag, $title, $description, $link;
if ($insideitem) {
switch ($tag) {
case ‘TITLE’:
$title .= $data;
break;
case ‘SUMMARY’:
$description .= $data;

break;
case ‘URL’:
$link .= $data;
break;
}
}
}
#Call this function
function yahoo_search($query, $appkey, $type=’web’) {
$type = strtolower($type);
$datafile = ‘http://api.search.yahoo.com/’.ucfirst($type).”SearchService/V1/{$type}Search?

appid=$appkey&query=”.$query;
// Create an XML parser
$xml_parser = xml_parser_create();
// Set the functions to handle opening and closing tags
xml_set_element_handler($xml_parser, ’startElement’, ‘endElement’);
// Set the function to handle blocks of character data
xml_set_character_data_handler($xml_parser, ‘characterData’);
// Open the XML file for reading
$fp = fopen($datafile,’r')
       or die(‘Error reading RSS data.’);
// Read the XML file 4KB at a time
while ($data = fread($fp, 4096))
   // Parse each 4KB chunk with the XML parser created above
   xml_parse($xml_parser, $data, feof($fp))
       // Handle errors in parsing
       or die(sprintf(“XML error: %s at line %d”,  
           xml_error_string(xml_get_error_code($xml_parser)),  
           xml_get_current_line_number($xml_parser)));
// Close the XML file
fclose($fp);
// Free up memory used by the XML parser
xml_parser_free($xml_parser);
}
#CHE4EVER
?>

Instructions

The script is called by yahoo_search($query, $appkey, $type=’web’). See Yahoo for different types. $appkey is your Yahoo Application key.