I am reading some xml which has come back from amazon's api. Most times amazon provides a list of similar products in their xml, but not always. If there are similar products I echo our them as a set of links. The problem is that not all products have similar products in the xml. I would like to change this code so that it checks if there are similar products nodes first and then if there are it continues to render them out as links as below but if not it just does nothing. The code below currently gives the following error message if there are no similar products in the xml:
Warning: Invalid argument supplied for foreach() in /public_html/product.php on line 26
if there are no similar product nodes in the xml returned from amazon.
Thanks in advance.
foreach ($result->Items->Item->SimilarProducts->SimilarProduct as $SimilarProduct) {
echo "<li><a href=\"product.php?prod=" . $SimilarProduct->ASIN . "\">" . $SimilarProduct->Title . "</a></li/> \n";
}
You can do this test before the foreach (note the if):
if ($result->Items->Item->SimilarProducts->SimilarProduct !== null)
{
foreach ($result->Items->Item->SimilarProducts->SimilarProduct as $SimilarProduct) {
echo "<li><a href=\"product.php?prod=" . $SimilarProduct->ASIN . "\">" . $SimilarProduct->Title . "</a></li/> \n";
}
}
Anyway this test works if there're no errors or null vars before the 'SimilarProduct'
(for example if 'Item'
is null the script will fail anyway).
Note: I suggest you to not do this kind of things, I mean this repeated access to vars (that is ->...->...->) because you will have a low control on the situation and on what's happening.