Our new member
Daniel Wiegand (wiegi) implemented a PEAR compatible client for Yahoo's new REST-based
webservice API. From the Yahoo developer site: "Yahoo! Search Web Services allow you to access Yahoo content and services in your favorite programming languages. This means you can now build Yahoo directly into your own applications." By using Daniel's PHP5 client you do not need to worry about the protocol or the resulting XML format, everything is done in plain PHP:
<?PHP
$yahoo = new Services_Yahoo($appId);
try {
// do a simple search
$result = $yahoo->searchWeb('PEAR');
echo "Total results returned: " . $result->getTotal() . "<br />\n";
foreach ($result as $entry) {
printf('<a href="%s">%s</a><br />', $entry['ClickUrl'], $entry['Title']);
printf('<i>%s</i><br /><br />', $entry['Summary']);
}
} catch (Services_Yahoo_Exception $e){
echo $e;
}
?>
Besides
searchWeb() the client provides more methods to use the different web services offered by Yahoo:
- searchImages()
- searchVideos()
- searchNews
- searchLocal()
Each of the methods can be used with several parameters that need to be passed in a fixed parameter order or you may pass a associative array that contains any parameters you want to pass.
As Daniel has been using PHP5 all of these methods return a
Services_Yahoo_Result object that provides methods to return the total number of search results but can be iterated like a normal object, thanks to SPL. This result object offers a lot more, as you can use it to fetch the next page using the same search parameters:
<?PHP
$yahoo = new Services_Yahoo($appId);
try {
// do a simple search
$result = $yahoo->searchWeb('Graceland');
printf("Total results returned: %d<br />\n", $result->getTotal());
printf("Fetching %d entries starting from %d.<br />\n", $result->getReturned(), $result->getCurrent());
foreach ($result as $entry) {
printf('<a href="%s">%s</a><br />', $entry['ClickUrl'], $entry['Title']);
printf('<i>%s</i><br /><br />', $entry['Summary']);
}
echo "Test, whether more entries are available....<br /><br />\n";
if ($result->hasNext()) {
$result->fetchNext();
}
printf("Fetching %d entries starting from %d.<br />\n", $result->getReturned(), $result->getCurrent());
foreach ($result as $entry) {
printf('<a href="%s">%s</a><br />', $entry['ClickUrl'], $entry['Title']);
printf('<i>%s</i><br /><br />', $entry['Summary']);
}
} catch (Services_Yahoo_Exception $e){
echo $e;
}
?>Quite cool, isn't it?
You can take a loot at the sources at
http://pear.php-tools.net/projects/Services_Yahoo/ or even download a PEAR installable package from
http://pear.php-tools.net/projects/Services_Yahoo/Services_Yahoo-0.1.0.tgz (requires PHP5, XML_Serializer and HTTP_Request).
We would have loved to propose this to PEAR, but there already is a draft for a Services_Yahoo package by Martin Jansen, but until now he hasn't showed any of his code. Hopefully Daniel and Martin could be working on a package together.