Yahoo Search API问题

时间:2011-04-22 05:43:32

标签: php yahoo-search

我遇到了雅虎搜索API的问题,有时候它会起作用,有时也不会导致我遇到问题

我正在使用此网址

  

http://api.search.yahoo.com/WebSearchService/rss/webSearch.xml?appid=yahoosearchwebrss&query=originurlextension%3Apdf+ $搜索&安培; adult_ok = 1&安培;开始= $启动

代码如下:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">   
<? $search = $_GET["search"]; 
$replace = " "; $with = "+"; 
$search = str_replace($replace, $with, $search);
if ($rs =
    $rss->get("http://api.search.yahoo.com/WebSearchService/rss/webSearch.xml?appid=yahoosearchwebrss&query=originurlextension%3Apdf+$search&adult_ok=1&start=$start")
    )
    {   }   
    // Go through the list powered by the search engine listed and get
    // the data from each <item>
    $colorCount="0";
    foreach($rs['items'] as $item)      {       // Get the title of result     
       $title = $item['title'];     // Get the description of the result
       $description = $item['description'];     // Get the link eg amazon.com 
       $urllink = $item['guid'];   
       if($colorCount%2==0) { 
         $color = ROW1_COLOR; 
       } else { 
          $color = ROW2_COLOR; 
       }   
       include "resulttemplate.php"; $colorCount++; 
       echo "\n";  
    }  
 ?>

有时它会产生结果,有时则不会。我通常会收到此错误

  

警告:在第14行的/home4/thesisth/public_html/pdfsearchmachine/classes/rss.php中为foreach()提供的参数无效

任何人都可以提供帮助..

1 个答案:

答案 0 :(得分:0)

错误Warning: Invalid argument supplied for foreach() in /home4/thesisth/public_html/pdfsearchmachine/classes/rss.php on line 14表示foreach构造没有收到可迭代的(通常是数组)。在你的情况下,这意味着$rs['items']是空的......也许搜索没有返回结果?

我建议首先在$rss->get("...")的结果中添加一些检查,并在请求失败或没有返回结果时执行操作:

<?php
$search = isset($_GET["search"]) ? $_GET["search"] : "default search term";
$start = "something here"; // This was left out of your original code
$colorCount = "0";
$replace = " ";
$with = "+"; 
$search = str_replace($replace, $with, $search);
$rs = $rss->get("http://api.search.yahoo.com/WebSearchService/rss/webSearch.xml?appid=yahoosearchwebrss&query=originurlextension%3Apdf+$search&adult_ok=1&start=$start");

if (isset($rs) && isset($rs['items'])) {
    foreach ($rs['items'] as $item) {
        $title       = $item['title'];       // Get the title of the result
        $description = $item['description']; // Get the description of the result 
        $urllink     = $item['guid'];        // Get the link eg amazon.com
        $color       = ($colorCount % 2) ? ROW2_COLOR : ROW1_COLOR; 
        include "resulttemplate.php";
        echo "\n";
        $colorCount++; 
    }
}
else {
    echo "Could not find any results for your search '$search'";
}

其他变化:

  • $ start未在$rss->get("...")来电
  • 之前宣布
  • $color if / else子句复合到三元运算中,并进行较少的比较
  • 我不确定if ($rs = $rss->get("...")) { }的目的是什么,所以我删除了它。

我还建议使用require而不是include,因为如果resulttemplate.php不存在会导致致命错误,我认为这是一种比PHP警告更好的方法来检测错误这将继续执行。但是我不了解你的整体情况所以它可能没什么用处。

希望有所帮助!

干杯

相关问题