美国东部时间3月1日,雅虎公司联合创始人之一的杨致远将宣布公司的搜索网络将进入Web服务。雅虎公司在 www.developer.yahoo.com 网站建立了Yahoo Search Developer Network,公司计划在此纽约举行的搜索引擎战略大会(Search Engine Strategies Conference)上推出这一计划。该网络将允许开发者在雅虎搜索之上建立新的应用程序,其中包括图像、视频、新闻以及地区搜索等内容。想要使用这项服务的会员必须先去 http://api.search.yahoo.com/webservices/register_application 申请一个自已的ID号,注:每个ID号每天只能搜索5000次。
下面我们看一下,如何用PHP脚本调用Yahoo! Search API实现搜索的效果,全部脚本如下:
1
2// Yahoo Web Services PHP Example Code
3// Rasmus Lerdorf
4
5$appid = 'YahooDemo';
6// 在这输入你申请的ID号
7
8$service = array('image'=>'http://api.search.yahoo.com/ImageSearchService/V1/imageSearch',
9'local'=>'http://api.local.yahoo.com/LocalSearchService/V1/localSearch',
10'news'=>'http://api.search.yahoo.com/NewsSearchService/V1/newsSearch',
11'video'=>'http://api.search.yahoo.com/VideoSearchService/V1/videoSearch',
12'web'=>'http://api.search.yahoo.com/WebSearchService/V1/webSearch');
1<html>
2<head><title>PHP Yahoo Web Service Example Code</title></head>
3<body>
4<form action="YahooSearchExample.php" method="GET">
5Search Term: <input name="query" type="text"/><br/>
6Zip Code: <input name="zip" type="text"/> (for local search)<br/>
7<input type="submit" value=" Go! "/>
8<select name="type">
foreach($service as $name => $val) {
if(!empty($_REQUEST['type']) && $name == $_REQUEST['type'])
echo "<option selected="">$name</option>\n";
else echo "<option>$name</option>\n";
}
1</select>
2</form>
function done() {
1</body></html>
1
2exit;
3}
4
5if(empty($_REQUEST['query']) || !in_array($_REQUEST['type'],array_keys($service))) done();
6
7// Ok, here we go, we have the query and the type of search is valid
8// First build the query
9$q = '?query='.rawurlencode($_REQUEST['query']);
10if(!empty($_REQUEST['zip'])) $q.="&zip=".$_REQUEST['zip'];
11if(!empty($_REQUEST['start'])) $q.="&start=".$_REQUEST['start'];
12$q .= "&appid=$appid";
13
14// Then send it to the appropriate service
15$xml = file_get_contents($service[$_REQUEST['type']].$q);
16
17// Parse the XML and check it for errors
18if (!$dom = domxml_open_mem($xml,DOMXML_LOAD_PARSING,$error)) {
19echo "XML parse error\n";
20foreach ($error as $errorline) {
21/* For production use this should obviously be logged to a file instead */
22echo $errorline['errormessage']."
<br/>
1\n";
2echo " Node : " . $errorline['nodename'] . "
<br/>
1\n";
2echo " Line : " . $errorline['line'] . "
<br/>
1\n";
2echo " Column : " . $errorline['col'] . "
<br/>
1\n";
2}
3done();
4}
5
6// Now traverse the DOM with this function
7// It is basically a generic parser that turns limited XML into a PHP array
8// with only a couple of hardcoded tags which are common across all the
9// result xml from the web services
10function xml_to_result($dom) {
11$root = $dom->document_element();
12$res['totalResultsAvailable'] = $root->get_attribute('totalResultsAvailable');
13$res['totalResultsReturned'] = $root->get_attribute('totalResultsReturned');
14$res['firstResultPosition'] = $root->get_attribute('firstResultPosition');
15
16$node = $root->first_child();
17$i = 0;
18while($node) {
19switch($node->tagname) {
20case 'Result':
21$subnode = $node->first_child();
22while($subnode) {
23$subnodes = $subnode->child_nodes();
24if(!empty($subnodes)) foreach($subnodes as $k=>$n) {
25if(empty($n->tagname)) $res[$i][$subnode->tagname] = trim($n->get_content());
26else $res[$i][$subnode->tagname][$n->tagname]=trim($n->get_content());
27}
28$subnode = $subnode->next_sibling();
29}
30break;
31default:
32$res[$node->tagname] = trim($node->get_content());
33$i--;
34break;
35}
36$i++;
37$node = $node->next_sibling();
38}
39return $res;
40}
41
42$res = xml_to_result($dom);
43
44// Ok, now that we have the results in an easy to use format,
45// display them. It's quite ugly because I am using a single
46// display loop to display every type and I don't really understand HTML
47$first = $res['firstResultPosition'];
48$last = $first + $res['totalResultsReturned']-1;
49echo "
<p>Matched ${res[totalResultsAvailable]}, showing $first to $last</p>
1\n";
2if(!empty($res['ResultSetMapUrl'])) {
3echo "
<p>Result Set Map: <a href='"${res[ResultSetMapUrl]}"'>${res[ResultSetMapUrl]}</a></p>
1\n";
2}
3for($i=0; $i<$res['totalResultsReturned']; $i++) {
4foreach($res[$i] as $key=>$value) {
5switch($key) {
6case 'Thumbnail':
7echo "
<img height='"${value[Height]}"' src='"${value[Url]}"' width='"${value[Width]}"'/>
1\n";
2break;
3case 'Cache':
4echo "Cache:
<a href='"${value[Url]}"'>${value[Url]}</a>
1[${value[Size]}]
<br/>
1\n";
2break;
3case 'PublishDate':
4echo "
<b>$key:</b>
1".strftime('%X %x',$value);
2break;
3default:
4if(stristr($key,'url')) echo "
<a href='"$value"'>$value</a>
<br/>
1\n";
2else echo "
<b>$key:</b>
1$value
<br/>
1";
2break;
3}
4}
5echo "
<hr/>
1\n";
2}
3
4// Create Previous/Next Page links
5if($start > 1)
6echo '
<a href="/YahooSearchExample.php'.
'?query='.rawurlencode($_REQUEST['query']).
'&zip='.rawurlencode($_REQUEST['zip']).
'&type='.rawurlencode($_REQUEST['type']).
'&start='.($start-10).'"><-Previous Page</a>
1';
2if($last < $res['totalResultsAvailable'])
3echo '
<a href="/YahooSearchExample.php'.
'?query='.rawurlencode($_REQUEST['query']).
'&zip='.rawurlencode($_REQUEST['zip']).
'&type='.rawurlencode($_REQUEST['type']).
'&start='.($last+1).'">Next Page-></a>
1';
2done();