1

我在使用 yahoo 搜索 API 时遇到问题,有时它可以工作,有时却不能,为什么我会遇到问题

我正在使用这个网址

http://api.search.yahoo.com/WebSearchService/rss/webSearch.xml?appid=yahoosearchwebrss&query=originurlextension%3Apdf+ $search&adult_ok=1&start=$start

代码如下:

<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() 提供的参数无效

任何人都可以帮助..

4

1 回答 1

0

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

我建议在$rss->get("...")first 的结果中添加一些检查,并在请求失败或不返回任何结果时采取措施:

<?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'";
}

其他变化:

  • $rss->get("...")$start 在您的通话之前未声明
  • 将 if/else 子句复合$color成一个三元运算,比较少
  • 我不确定它的目的是什么if ($rs = $rss->get("...")) { },所以我删除了它。

我还建议使用require而不是,include因为如果 resulttemplate.php 不存在,它会导致致命错误,在我看来,这比 PHP 警告更好地检测错误,它将继续执行。但是,我不了解您的整个情况,因此它可能没有太大用处。

希望有帮助!

干杯

于 2011-04-22T21:24:35.263 回答