Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
  • 💬 Discuss
Like this article? We recommend

Web Service Examples

Now let's walk through an example of a PHP-based application for integrating with each of the five web services. To create and run these examples, I used the following test server environment:

  • Linux with Apache web server
  • PHP version 4.3.10 compiled --with-dom and --with-xml enabled

Specifically, the function xml_to_result($dom) is used from Rasmus Lerdorf's sample code in the Yahoo! API SDK (see step 3 in the earlier section "Getting Started") and referenced in all code here as require('xml_to_dom.php'). For a couple of the web services examples, spelling and contextual search, the following PHP functions were used to parse the returned XML results from the REST query:

xml_parser_create()
xml_parser_into_struct()
xml_parser_free()

The $ApplicationID variable value used in all examples is the application ID that Yahoo! provides in step 1 of the process described in the earlier section "Getting Started."

Image Search

Purpose: Random images of the moment, selected by keyword(s).

Description: With each page refresh, a randomized set of the top five images will be returned by keyword (see Figure 1).

Figure 1

Figure 1 Image search.

And now, the code:

<?php
require('xml_to_dom.php'); // this gets the xml_to_dom function
$ApplicationID = 'this is your Yahoo ApplicationID'; // see step 1
$image_keywords = array('sun','space','water','cars'); // random keywords, put whatever you like here
mt_srand(time()); // seed randomizer
$random_index = mt_rand(1, (count($image_keywords))) - 1; // get a random keyword from $images_keywords
$keyword_chosen = $image_keywords[$random_index]; // set random keyword

######## CREATE QUERY ######################
$q = '?query='.rawurlencode($keyword_chosen); // set query parameter to the random keyword chosen
$q = '&results=5'; // get only 5 results (default is 10, max request is 20 results at a time)
$q .= "&appid=$ApplicationID"; // add the required appid (ApplicationID) parameter

// submit the query ($q) to the Image API
$xml = file_get_contents('http://api.search.yahoo.com/ImageSearchService/V1/imageSearch'.$q);
$dom = domxml_open_mem($xml,DOMXML_LOAD_PARSING,$error);
$res = xml_to_result($dom);

######## DISPLAY RESULTS ######################
// determine how many results are returned and show, at most, five results
$num_results = 5;
if( $res['totalResultsReturned'] < 5 ) {
$num_results = $res['totalResultsReturned'];
}

// add required attribution to Yahoo! search
$domhtml = "<i>powered by <a href=\"http://www.yahoo.com/\">Yahoo! search</a>";

// display the total number of results matching the image query
$domhtml .= <br />Matched ${res[totalResultsAvailable]}<br />Top <b>$num_results</b> Results<br /><br />\n";

// loop through the (max) five results, and grab the components needed to assemble the output:
// ClickUrl for the url of the big picture, the Thumbnail Url, Height and Width, and the Title for the ALT tag
for($i=0; $i$value) {
    switch($key) {
    case 'Thumbnail':
        $Thumbnail["Url"] = $value['Url'];
        $Thumbnail["Height"] = $value['Height'];
        $Thumbnail["Width"] = $value['Width'];
    break;
      case 'ClickUrl':
        $clickUrl = $value;
      break;
      case 'Title':
        $Title = $value;
      break;
    }
  }
  // assemble the components into a clickable image that opens in a new browser window
  $domhtml .= "<a href=\"$clickUrl\" target=\"_blank\"><img src='" . $Thumbnail['Url'] . "' ALT='$Title' height='" . $Thumbnail['Height'] . "'width='" . $Thumbnail['Width'] . "' border='0' /></a> ";
}
// output the centered HTML output to the browser
print "<center>$domhtml</center>"; // we're done!
?>

A loop is not needed to access the elements in the multidimensional array. For example, to reference the first search result click_url and thumbnail URL, the following PHP code could be used:

echo $res[0]['ClickUrl'];
echo $res[0]['Thumbnail']['Url'];

The next example shows this being done.

Local Search

Purpose: Find local movie theaters or other businesses by ZIP code in a 20-mile radius.

Description: Form to select business and ZIP code (see Figure 2).

Figure 2

Figure 2 Local search.

Here's the code:

<?php
require('xml_to_dom.php'); // this gets the xml_to_dom function
$ApplicationID = 'this is your Yahoo ApplicationID'; // see step 1
?>
<!-- HTML code for the form -->
Find local movie theaters in a 20-mile radius:<br />
<form action="search-local-example.php" method="GET">
Search for business: <input type="text" value="movie theaters" name="query" /> (movie theaters, banks, etc.)<br />
Address (Zip code or *other): <input type="text" value="<?php echo($_GET['location']);?>" name="location" /> <input type="submit" value=" Go! " /><br />
*Other valid address entries include: <ul>
<li>city, state</li>
<li>city, state, ZIP</li>
<li>street, city, state</li>
<li>street, city, state, ZIP</li>
<li>street, ZIP</li>
</ul>
</form>
<!-- end HTML code for the form -->
<?php
####### CREATE QUERY, IF FORM FILLED OUT ####
if($_GET['location'] != '' AND $_GET['query'] != '') {

$q = '?query='.rawurlencode($_GET['query']); // send parameter for business: movie theaters, banks, etc.
$q .= '&location='.rawurlencode($_GET['location']); // send parameter for location in proper format
$q .= '&radius=20'; // send results for 20-mile radius
$q .= "&appid=$ApplicationID"; // required ApplicationID

// note the different REST URL for localSearch
$xml = file_get_contents('http://api.local.yahoo.com/LocalSearchService/V1/localSearch'.$q);
$dom = domxml_open_mem($xml,DOMXML_LOAD_PARSING,$error);
$res = xml_to_result($dom);

$num_results = 10; // default, but if less than 10 redefine
if( $res['totalResultsReturned'] < 10 ) {
  $num_results = $res['totalResultsReturned'];
}

######## DISPLAY RESULTS ######################
// show number of results and rank by distance from location entered
$domhtml = "Matched ${res[totalResultsAvailable]}<br /><b>$num_results</b> Results displayed (ranked by distance from ${_GET['location']})<br /><br />\n";

// loop through results and format the HTML
for($i=0; $i' . ($i+1) . '.</b> <a href="' . $res[$i]['ClickUrl'] . '" target="_blank">' . $res[$i]['Title'] . '</a><br />';
  $domhtml .= $res[$i]['Address'] . '<br />';
  $domhtml .= $res[$i]['City'] . ', ' . $res[$i]['State'] . '<br /><b>';
  $domhtml .= $res[$i]['Phone'] . '</b><br /> approximately ';
  $domhtml .= $res[$i]['Distance'] . ' mile(s) <br /><br />';
}

// output to HTML with the required 'powered by Yahoo! search' right-aligned
print "$domhtml<p align=\"right\"><i>powered by Yahoo! search</i></p>";
}
?>

News Search

Purpose: Top 25 headlines by keyword in selectable languages, sorted by most recent.

Description: Form to select keyword and supported languages (see Figure 3).

Figure 3

Figure 3 News search.

I used this code:

<?php
require('xml_to_dom.php'); // this gets the xml_to_dom function
$ApplicationID = 'this is your Yahoo ApplicationID'; // see step 1

// fill array of valid languages: http://developer.yahoo.net/documentation/languages.html
$valid_languages = array("arabic"=>'ar', "bulgarian"=>'bg',
  "catalan"=>'ca',"chinese-simplified"=>'szh',
  "chinese-traditional"=>'tzh',"croatian"=>'hr',
  "czech"=>'cs',"danish"=>'da',
  "dutch"=>'nl',"english"=>'en',
  "estonian"=>'et',"finnish"=>'fi',
  "french"=>'fr',"german"=>'de',
  "greek"=>'el',"hebrew"=>'he',
  "hungarian"=>'hu',"icelandic"=>'is',
  "indonesian"=>'id',"italian"=>'it',
  "japanese"=>'ja',"korean"=>'ko',
  "latvian"=>'lv',"lithuanian"=>'lt',
  "norwegian"=>'no',"persian"=>'fa',
  "polish"=>'pl',"portuguese"=>'pt',
  "romanian"=>'ro',"russian"=>'ru',
  "slovak"=>'sk',"serbian"=>'sr',
  "slovenian"=>'sl',"spanish"=>'es',
  "swedish"=>'sv',"thai"=>'th',
  "turkish"=>'tr');
?>
Find 10 most recent headlines by keyword(s) in multiple languages:<br />
<form action="search-news-example.php" method="GET">
News subject/topic: <input type="text" value="Yahoo" name="query" /> <br />
Language: <select name="language">
<option SELECTED value="en">English (default)</option>
<?php
// populate the drop-down menu from the $valid_languages array
foreach($valid_languages as $key=>$value) {
  print "<option value=\"$value\">$key</option>\n";
}
?>
</select> <input type="submit" value=" Go! " />
</form>

<?php
####### CREATE QUERY ##########################
if($_GET['query'] != '') {
$q = '?query='.rawurlencode($_GET['query']); // keywords
$q .= '&language='.rawurlencode($_GET['language']); // language chosen from drop-down menu by user
$q .= '&sort=date'; // sort by date instead of the default (relevance)
$q .= '&results=25'; // get 25 results instead of the default 10, max is 50
$q .= "&appid=$ApplicationID"; // required ApplicationID

// Note different REST URL for newsSearch
$xml = file_get_contents('http://api.search.yahoo.com/NewsSearchService/V1/newsSearch'.$q);
$dom = domxml_open_mem($xml,DOMXML_LOAD_PARSING,$error);
$res = xml_to_result($dom);

$num_results = 25;
// if less than 25 results, show actual results
if( $res['totalResultsReturned'] < 25 ) {
  $num_results = $res['totalResultsReturned'];
}

######## DISPLAY RESULTS ######################
$domhtml = "Matched ${res[totalResultsAvailable]}<br />
<b>$num_results</b> Results displayed (ranked by date)<br /><br />\n";

for($i=0; $i' . ($i+1) . '.</b> <a href="' . $res[$i]['ClickUrl'] . '" target="_blank">' . $res[$i]['Title'] . '</a><br />';
  $domhtml .= $res[$i]['Summary'] . '<br /><i>Source: ';
  $domhtml .= '<a href="' . $res[$i]['NewsSourceUrl'] . '" target="_blank">' . $res[$i]['NewsSource'] . '</a> published on ' . date("m-d-Y h:i", $res[$i]['PublishDate']);
  $domhtml .= '</i><br /><br />';
}
print "$domhtml<p align=\"right\"><i>powered by Yahoo! search</i></p>";
}
?>

Video Search

Purpose: Find videos on the web by format and keyword(s).

Description: Form to input keyword(s) and video format (see Figure 4).

Figure 4

Figure 4 Video search.

This is the code:

<?php
require('xml_to_dom.php'); // this gets the xml_to_dom function
$ApplicationID = 'this is your Yahoo ApplicationID'; // see step 1
?>
Find videos by keyword(s) and format:<br />
<form action="search-video-example.php" method="GET">
Keywords: <input type="text" value="<?php echo($_GET['query']);?>" name="query" /> Type results: <input type="radio" checked name="type" value="all"> all
<input type="radio" name="type" value="any"> any
<input type="radio" name="type" value="phrase"> phrase<br />
Format: <select name="format">
<option SELECTED value="any">Any</option>
<option value="avi">avi</option>
<option value="flash">flash</option>
<option value="mpeg">mpeg</option>
<option value="mpeg">msmedia</option>
<option value="quicktime">quicktime</option>
<option value="realmedia">realmedia</option>
</select> <input type="submit" value=" Go! " />
</form>

<?php
####### CREATE QUERY ##########################
if($_GET['query'] != '') {
$q = '?query='.rawurlencode($_GET['query']);
$q .= '&type='.rawurlencode($_GET['type']); // default is all, but can be any or phrase
$q .= '&format='.rawurlencode($_GET['format']); // type of media format to search for
$q .= "&appid=$ApplicationID"; // required ApplicationID

$xml = file_get_contents('http://api.search.yahoo.com/VideoSearchService/V1/videoSearch'.$q);
$dom = domxml_open_mem($xml,DOMXML_LOAD_PARSING,$error);
$res = xml_to_result($dom);

$num_results = 10; // default is 10, max is 50 results
if( $res['totalResultsReturned'] < 10 ) {
  $num_results = $res['totalResultsReturned'];
}

######## DISPLAY RESULTS ######################
$domhtml = "Total matched ${res[totalResultsAvailable]}<br /><b>$num_results</b> Video Results displayed<br /><br />\n";

for($i=0; $i' . ($i+1) . '.</b> <a href="' . $res[$i]['ClickUrl'] . '" target="_blank">' . $res[$i]['Title'] . '</a><br />';
  $domhtml .= $res[$i]['Summary'] . '<br /> ';
  $domhtml .= $res[$i]['FileSize'] . ' bytes <b>';
  $domhtml .= $res[$i]['FileFormat'];
  $domhtml .= '</b><br /><br />';
}
print "$domhtml<p align=\"right\"><i>powered by Yahoo! search</i></p>";
}
?>

Web Search

Purpose: Spell check, contextual search, Creative Commons content search, main web search, demonstrating pagination (providing links to previous and next for multiple-page results).

Description: Form to select the type of search and keyword(s) or word to spell check or provide related queries, also demonstrating previous and next page.

Figure 5 shows an example of a spell check. Figure 6 shows a context search. Figure 7 shows a Creative Commons example.

Figure 5

Figure 5 Spell check.

Figure 6

Figure 6 Context search.

Figure 7

Figure 7 Creative Commons search.

Currently, the web search provides by far the most flexibility of all the web services. The main web search service can be broken into six subcategories:

  • Web Search includes narrowing searches by Creative Commons licensed content (see http://search.yahoo.com/cc) as well as searching the Yahoo! search index.
  • Related Queries returns possible related queries based on the current search keyword(s) or phrases.
  • Spelling Suggest checks the spelling of a word and offers possible corrections.
  • Misspelling Suggest is an April Fool's joke version of Spelling Suggest, which intentionally returns a misspelled version of a correctly spelled string.
  • Context Search is for evaluating a larger amount of text and finding the contextual meaning.
  • Content Analysis and Text Extraction doesn't specifically fit under the web services category, and Yahoo! currently has it in its own category. I've grouped it here for familiarity with Context Search and Related Queries. It uses its own REST URL:
http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction

Let's take a look at the application to demo web services:

<?php
require('xml_to_dom.php'); // this gets the xml_to_dom function
$ApplicationID = 'this is your Yahoo ApplicationID'; // see step 1

// below we'll create the HTML form with various search options
?>
<b>Perform multiple types of Yahoo web services searches</b>
<form action="search-web-example.php" method="GET">
Keyword(s)/word/phrase: <input type="text" value="<?php echo($_GET['query']);?>" name="query" /> <br />
Do the following: <select name="doit">
<option SELECTED value="other">Find web sites (default)</option>
<option value="creative_commons">Find Creative Commons licensed content (any)</option>
<option value="related_queries">Find related queries</option>
<option value="spellcheck">Check spelling</option>
</select> <input type="submit" value=" Go! " />
</form>

<?php
####### CREATE QUERY ##########################
if($_GET['query'] != '') {
$q = '?query='.rawurlencode($_GET['query']);
$q .= '&start='.rawurlencode($_GET['start']);
// choose the correct REST URL chosen by the user
$service_url = 'http://api.search.yahoo.com/WebSearchService/V1/webSearch';
switch ($_GET['doit']) {
  case 'creative_commons':
    $q .= '&license=cc_any'; // other options include cc_commercial and cc_modifiable
  break;
  case 'related_queries':
    $service_url = 'http://api.search.yahoo.com/WebSearchService/V1/relatedSuggestion';
  break;
  case 'spellcheck':
    $service_url = 'http://api.search.yahoo.com/WebSearchService/V1/spellingSuggestion';
  break;
}

// end the query
$q .= "&appid=$ApplicationID"; // required ApplicationID
$xml = file_get_contents("$service_url$q"); // parse the proper webservice + query

if($_GET['doit'] == 'related_queries' OR $_GET['doit'] == 'spellcheck') {
  // use basic XML parser for contextual search and spell checking
  $parser = xml_parser_create();
  xml_parse_into_struct($parser,$xml,&$structure,&$index);
  xml_parser_free($parser);
  $i = 0;
  foreach($structure as $s) {
    if($s["level"] == 2) {
      // load the results into $res variable
      $res[$i] = $s["value"];
      $i++;
    }
  }

} else {
  // use DOM for the other REST results
  $dom = domxml_open_mem($xml,DOMXML_LOAD_PARSING,$error);
  $res = xml_to_result($dom);
}

######## DISPLAY RESULTS ######################
if($_GET['doit'] == 'related_queries' OR $_GET['doit'] == 'spellcheck') {
  $domhtml = 'Word checked: ' . $_GET['query'];
  if($_GET['doit'] == 'spellcheck') {
    $domhtml .= "<br/>Possible correct spelling(s): <b>";
    for($i=0; $i<count($res); $i++) {
      $domhtml .= "$res[$i] ";
    }
    $domhtml .= "</b><br />";
  } else {
    // must be contextual search
    $domhtml .= "<br/>Other contextually related keyword(s)/phrase(s): <ul><b>";
    for($i=0; $i<count($res); $i++) {
      $domhtml .= "<li><a href=\"search-web-example.php?query=" . rawurlencode($res[$i]) . "&doit=related_queries\">$res[$i]</a></li>";
    }
    $domhtml .= "</b></ul>";
  }
} else {
  $first = $res['firstResultPosition']; // important to know for pagination
  $last = $first + $res['totalResultsReturned']-1;
  $num_results = 25;
  if( $res['totalResultsReturned'] < 25 ) {
    $num_results = $res['totalResultsReturned'];
  }
  // using a generic output for all default web services results
  $domhtml = "Matched ${res[totalResultsAvailable]}<br /><b>$num_results</b> Results displayed (ranked by relevance)<br /><br />\n";
  for($i=0; $i' . ($i+1) . '.</b> <a href="' . $res[$i]['ClickUrl'] . '" target="_blank">' . $res[$i]['Title'] . '</a><br />';
    $domhtml .= $res[$i]['Summary'] . '<br />';
    $domhtml .= '<br />';
  }
}

// output the results and the required Yahoo! attribution right-aligned
print "$domhtml<p align=\"right\"><i>powered by Yahoo! search</i></p>";

/* pagination for previous / next links if there are more results
  REMEMBER: no more than 1,000 results for most queries */
if($start > 1)
print "<a href=\"search-web-example.php?query=" . rawurlencode($_GET['query']) . '&doit=' . rawurlencode($_GET['doit']) . '&start='.($start-10).'">&lt;-Previous Page</a> &nbsp; ';
if($last < $res['totalResultsAvailable'])
print "<a href=\"search-web-example.php?query=" . rawurlencode($_GET['query']) . '&doit=' . rawurlencode($_GET['doit']) . '&start='.($last+1).'">Next Page-&gt;</a>';
}
?>

This article should provide programmers with a good idea of the flexibility of the Yahoo! API. This API continues to evolve, as mentioned at the beginning of the article. There are certain to be more changes, but as these changes come along developers can follow along on the various web service mailing lists. In fact, Yahoo! recently added support for their new MyWeb API, which allows searching through folders of links people have bookmarked and shared publicly via the Yahoo Toolbar and Search.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus