插件75:读取Yahoo! Answers


<?php // Plug-in 75: Get Yahoo! Answers
/*
 * 获取Yahoo!Answers
 * 插件说明:
 * 插件接受一个搜索关键词,返回在Yaoo!Answers上找到的结果。
 * 若操作成功,则返回一个两元素数组,第一个元素值为返回的问答题的个数,第二个参数是一个数组,
 * 数组的每个元素又是一个子数组,子数组含有以下五个值:
 *     主题
 *     Unix时间戳,表示该问题发帖的时间
 *     题目
 *     答案
 *     指向原来的Q&Q的URL地址
 * 若操作失败,则返回单个元素的数组,元素值为FALSE。
 * 本插件需要以下参数:
 * $search 搜索串
 */
// This is an executable example with additional code supplied
// To obtain just the plug-ins please click on the Download link

$search = "gardening tips";
$result = PIPHP_GetYahooAnswers($search);

if (!$result[0]) echo "No matching questions found for $search.";
else
   foreach($result[1] as $qa)
      echo "<b>$qa[0]</b> (" . date('M \'y', $qa[1]) . ')<br />'.
           "<b>Q.</b> <i>$qa[2]</i><br />" .
           "<b>A.</b> $qa[3]<br />" .
           "<a href='$qa[4]'>Original Question</a><br /><br />";

function PIPHP_GetYahooAnswers($search)
{
   // Plug-in 75: Get Yahoo! Answers
   //
   // This plug-in fetches a collection of questions and answers
   // from Yahoo! Answers based on the query passed in $search.
   // Upon success it returns a two element array with the first
   // value being the number of Q&As returned and the second
   // an array containing the sets of Q&As. This array contains
   // sub-arrays for the elements of each Q&A with these items:
   // 1) Subject, 2) Timestamp, 3) Question, 4) Answer, 5) URL.
   // Yahoo! Web Search web services are limited to 5,000 queries
   // per IP per day, per API so you are recommended to cache
   // results where you can. It requires the following argument:
   //
   //    $search: A search query

   $search = rawurlencode($search);
   $id     = 'YahooDemo'; // Use your own API key here
   $url    = 'http://answers.yahooapis.com' .
             '/AnswersService/V1/questionSearch' .
             "?appid=$id&query=$search";
   $xml    = @file_get_contents($url);
   if (!$xml) return array(FALSE);

   $sxml   = simplexml_load_string($xml);
   $qandas = array();

   foreach($sxml->Question as $question)
   {
      $s = trim($question->Subject);
      $t = $question->Timestamp + 0;
      $q = trim($question->Content);
      $a = trim($question->ChosenAnswer);
      $l = $question->Link;
      
      $s = str_replace("\n", '<br />', htmlentities($s));
      $q = str_replace("\n", '<br />', htmlentities($q));
      $a = str_replace("\n", '<br />', htmlentities($a));

      if (strlen($a)) $qandas[] = array($s, $t, $q, $a, $l);
   }

   return array(count($qandas), $qandas);
}

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值