Discuz教程网

利用Yahoo Search API开发自已的搜索引擎-PHP版

[复制链接]
authicon dly 发表于 2011-8-28 09:43:52 | 显示全部楼层 |阅读模式
美国东部时间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. <?php
  2. // Yahoo Web Services PHP Example Code
  3. // Rasmus Lerdorf
  4. // www.knowsky.com
  5. $appid = 'YahooDemo';
  6. // 在这输入你申请的ID号
  7. $service = array('image'=>'http://api.search.yahoo.com/ImageSearchService/V1/imageSearch',
  8. 'local'=>'http://api.local.yahoo.com/LocalSearchService/V1/localSearch',
  9. 'news'=>'http://api.search.yahoo.com/NewsSearchService/V1/newsSearch',
  10. 'video'=>'http://api.search.yahoo.com/VideoSearchService/V1/videoSearch',
  11. 'web'=>'http://api.search.yahoo.com/WebSearchService/V1/webSearch');
  12. ?>
  13. <html>
  14. <head><title>PHP Yahoo Web Service Example Code</title></head>
  15. <body>
  16. <form action="YahooSearchExample.php" method="GET">
  17. Search Term: <input type="text" name="query" /><br />
  18. Zip Code: <input type="text" name="zip" /> (for local search)<br />
  19. <input type="submit" value=" Go! " />
  20. <select name="type">
  21. <?php foreach($service as $name => $val) {
  22. if(!empty($_REQUEST['type']) && $name == $_REQUEST['type'])
  23. echo "<option SELECTED>$name</option>\n";
  24. else echo "<option>$name</option>\n";
  25. } ?>
  26. </select>
  27. </form>
  28. <?php
  29. function done() {?>
  30. </body></html>
  31. <?php
  32. exit;
  33. }
  34. if(empty($_REQUEST['query']) || !in_array($_REQUEST['type'],array_keys($service))) done();
  35. // Ok, here we go, we have the query and the type of search is valid
  36. // First build the query
  37. $q = '?query='.rawurlencode($_REQUEST['query']);
  38. if(!empty($_REQUEST['zip'])) $q.="&zip=".$_REQUEST['zip'];
  39. if(!empty($_REQUEST['start'])) $q.="&start=".$_REQUEST['start'];
  40. $q .= "&appid=$appid";
  41. // Then send it to the appropriate service
  42. $xml = file_get_contents($service[$_REQUEST['type']].$q);
  43. // Parse the XML and check it for errors
  44. if (!$dom = domxml_open_mem($xml,DOMXML_LOAD_PARSING,$error)) {
  45. echo "XML parse error\n";
  46. foreach ($error as $errorline) {
  47. /* For production use this should obviously be logged to a file instead */
  48. echo $errorline['errormessage']."<br />\n";
  49. echo " Node : " . $errorline['nodename'] . "<br />\n";
  50. echo " Line : " . $errorline['line'] . "<br />\n";
  51. echo " Column : " . $errorline['col'] . "<br />\n";
  52. }
  53. done();
  54. }
  55. // Now traverse the DOM with this function
  56. // It is basically a generic parser that turns limited XML into a PHP array
  57. // with only a couple of hardcoded tags which are common across all the
  58. // result xml from the web services
  59. function xml_to_result($dom) {
  60. $root = $dom->document_element();
  61. $res['totalResultsAvailable'] = $root->get_attribute('totalResultsAvailable');
  62. $res['totalResultsReturned'] = $root->get_attribute('totalResultsReturned');
  63. $res['firstResultPosition'] = $root->get_attribute('firstResultPosition');
  64. $node = $root->first_child();
  65. $i = 0;
  66. while($node) {
  67. switch($node->tagname) {
  68. case 'Result':
  69. $subnode = $node->first_child();
  70. while($subnode) {
  71. $subnodes = $subnode->child_nodes();
  72. if(!empty($subnodes)) foreach($subnodes as $k=>$n) {
  73. if(empty($n->tagname)) $res[$i][$subnode->tagname] = trim($n->get_content());
  74. else $res[$i][$subnode->tagname][$n->tagname]=trim($n->get_content());
  75. }
  76. $subnode = $subnode->next_sibling();
  77. }
  78. break;
  79. default:
  80. $res[$node->tagname] = trim($node->get_content());
  81. $i--;
  82. break;
  83. }
  84. $i++;
  85. $node = $node->next_sibling();
  86. }
  87. return $res;
  88. }
  89. $res = xml_to_result($dom);
  90. // Ok, now that we have the results in an easy to use format,
  91. // display them. It's quite ugly because I am using a single
  92. // display loop to display every type and I don't really understand HTML
  93. $first = $res['firstResultPosition'];
  94. $last = $first + $res['totalResultsReturned']-1;
  95. echo "<p>Matched ${res[totalResultsAvailable]}, showing $first to $last</p>\n";
  96. if(!empty($res['ResultSetMapUrl'])) {
  97. echo "<p>Result Set Map: <a href="${res[ResultSetMapUrl]}">${res[ResultSetMapUrl]}</a></p>\n";
  98. }
  99. for($i=0; $i<$res['totalResultsReturned']; $i++) {
  100. foreach($res[$i] as $key=>$value) {
  101. switch($key) {
  102. case 'Thumbnail':
  103. echo "<img src="${value[Url]}" height="${value[Height]}" width="${value[Width]}" />\n";
  104. break;
  105. case 'Cache':
  106. echo "Cache: <a href="${value[Url]}">${value[Url]}</a> [${value[Size]}]<br />\n";
  107. break;
  108. case 'PublishDate':
  109. echo "<b>$key:</b> ".strftime('%X %x',$value);
  110. break;
  111. default:
  112. if(stristr($key,'url')) echo "<a href="$value">$value</a><br />\n";
  113. else echo "<b>$key:</b> $value<br />";
  114. break;
  115. }
  116. }
  117. echo "<hr />\n";
  118. }
  119. // Create Previous/Next Page links
  120. if($start > 1)
  121. echo '<a href="/YahooSearchExample.php'.
  122. '?query='.rawurlencode($_REQUEST['query']).
  123. '&zip='.rawurlencode($_REQUEST['zip']).
  124. '&type='.rawurlencode($_REQUEST['type']).
  125. '&start='.($start-10).'"><-Previous Page</a> ';
  126. if($last < $res['totalResultsAvailable'])
  127. echo '<a href="/YahooSearchExample.php'.
  128. '?query='.rawurlencode($_REQUEST['query']).
  129. '&zip='.rawurlencode($_REQUEST['zip']).
  130. '&type='.rawurlencode($_REQUEST['type']).
  131. '&start='.($last+1).'">Next Page-></a>';
  132. done();
  133. ?>
复制代码

有兴趣的朋友还可以看一下由[动态网站制作指南]所制作的ASP版本:http://www.knowsky.com/yahoo/





上一篇:PHP中检查email完整性
下一篇:用PHP实现标准的IP Whois查询
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-8-2 20:06

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表