O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  


 
Buy the book!
Yahoo! Hacks
By Paul Bausch
October 2005
More Info

HACK
#69
Program Yahoo! with PHP 5
Take advantage of some of the latest features in PHP to quickly add Yahoo! data to PHP-powered pages
The Code
[Discuss (0) | Link to this hack]

The Code

Save the following code to your web server in a file called yahoo_search.php.

TIP

Don't forget to grab a unique application ID for this script at http://developer.yahoo.net.

<?php
// yahoo_search.php
// Accepts a search term and shows the top results.
// Usage: yahoo_search.php?p=<Query>
//
// You can create an AppID, and read the full documentation
// for Yahoo! Web Services at http://developer.yahoo.net/

// Set your unique Yahoo! Application ID
$appID = "insert your app ID";

// Grab the incoming search query, and encode for a URL
$query = $_GET['p'];
$query = urlencode($query);

if ($query == "") { 
	print "usage: yahoo_search.php?p=&lt;Query&gt;"; die;
}

// Construct a Yahoo! Search Query with only required options
$language = "en";
$req_url = "http://api.search.yahoo.com/";
$req_url .= "WebSearchService/V1/webSearch?";
$req_url .= "appid=$appID";
$req_url .= "&query=$query";
$req_url .= "&language=$language";

// Make the request
$yahoo_response = file_get_contents($req_url);

// Parse the XML
$xml = simplexml_load_string($yahoo_response);

// Initialize results counter
$i = 0;
?>
<html>

<body>
<h2>Yahoo! Search Results</h2>
<ol>
<?php
// Loop through the items returned, printing them out
foreach ($xml->Result as $result) {
	$i++;
	$title = $result->Title;
	$summary = $result->Summary;
	$summary = preg_replace("/</i","&lt;",$summary);
	$clickurl = $result->ClickUrl;
	$url = $result->Url;
	print "<li><div style=\"margin-bottom:15px;\">";
	print "<a href=\"$clickurl\">$title</a><br />";
	print "$summary<br />";
	print "<cite>$url</cite></div></li>\n";

}
?>
</ol>
-- Results Powered by Yahoo!
</body>
</html>

This script uses the value of the querystring variable p to build a Yahoo! Web Search request URL and fetches the XML with the file_get_contents() function. Once the script has the XML in the $yahoo_response string, it calls the SimpleXML function simplexml_load_string( ), which parses the XML and makes the data available to PHP as an object. Finally, the script loops through the objects, using print to send the data to the browser.


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.