Jump to content

[SOLVED] Warning: Invalid argument supplied for foreach() in


newbtophp

Recommended Posts

Im using the Yahoo api, for my search script.

 

But sometimes I search something I get:

 

Warning: Invalid argument supplied for foreach() in /home/mysite/public_html/search.php on line 240

 

Heres the code which is causing the problem:

 

<?



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>

    foreach($rs['items'] as $item) { //this is line 240

// 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'];

include "templates/result.php";

echo "\n"; 

} 





?>

 

foreach() expects an array. When you don't supply it with an array you get that error message.

 

Your code has an if(...){...} conditional statement to test the results of the $rs = $rss->get() function call, but you have put the ending } on the line right after the line with the if() test. You should have put the } after your code that processes the data so that the code will only be executed when there is data to process. You should also have an else {} clause as part of the if(){} statement to output a message indicating that the search did not match anything.

if ($rs = $rss->get("http://api.search.yahoo.com/WebSearchService/rss/webSearch.xml?appid=yahoosearchwebrss&query=originurlextension%3Apdf+$search&adult_ok=1&start=$start")) {

    // code to execute when $rss->get() returns something

} else {

    // code to execute when $rss->get() does not return anything

}

Ok I've updated the code but I get an error:

 

Parse error: syntax error, unexpected T_ELSE in /home/mysite/public_html/search.php on line 261

 

<?php

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>

    foreach($rs['items'] as $item) { //this is line 240


// 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'];
   


include "templates/result.php";



} else {  //Line 261

    // code to execute when $rss->get() does not return anything

echo "Error!\n";

}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.