Search code examples
phpif-statementebay-api

IF Statement in eBay API


I have a PHP code to use eBay API to get 5 results by keyword.

I want to add an IF condition to show a headline <h2>List of products</h2> only if there are results.

    // Check to see if the request was successful, else print an error
if ($resp->ack == "Success") {
$results = '';
// If the response was loaded, parse it and build links  

foreach($resp->searchResult->item as $item) {
$pic   = $item->galleryPlusPictureURL;
$link  = $item->viewItemURL;
$title = $item->title;
$price = $item->sellingStatus->currentPrice;

// For each SearchResultItem node, build a link and append it to $results
$results .= "<tr><td style=\"text-align: center;\"><img width=\"300\"   src=\"$pic\"></td></tr><tr><td><a href=\"$link\" rel=\"nofollow\">$title</a></td></tr><tr><td style=\"text-align: right;\">".$price." &euro;&nbsp;&nbsp;<div><a href=\"$link\" rel=\"nofollow\"><p class=\"bux\">> Offer</p></a></div></td></tr>";
}
}
// If the response does not indicate 'Success,' print an error
else {
$results  = "<h3>Oops! The request was not successful. Make sure you are  using   a valid ";
$results .= "AppID for the Production environment.</h3>";
}

echo "<table>".$results."</table>";

How do I edit the code above in order to show <h2>List of products</h2> only if there is at least one result otherwise show nothing?


Solution

  • // Check to see if the request was successful, else print an error
    if ($resp->ack == "Success") {
        $results = '';
        // If the response was loaded, parse it and build links  
    
        foreach($resp->searchResult->item as $item) {
            $pic   = $item->galleryPlusPictureURL;
            $link  = $item->viewItemURL;
            $title = $item->title;
            $price = $item->sellingStatus->currentPrice;
    
           // For each SearchResultItem node, build a link and append it to  $results
            $results .= "<tr><td style=\"text-align: center;\"><img width=\"300\"   src=\"$pic\"></td></tr><tr><td><a href=\"$link\" rel=\"nofollow\">$title</a></td></tr><tr><td style=\"text-align: right;\">".$price." &euro;&nbsp;&nbsp;<div><a href=\"$link\" rel=\"nofollow\"><p class=\"bux\">> Offer</p></a></div></td></tr>";
        }
        if ( ! empty($results) )
            $results = '<h2>List of products</h2>'. $results;
    }
    // If the response does not indicate 'Success,' print an error
    else {
        $results  = "<h3>Oops! The request was not successful. Make sure you are  using   a valid ";
        $results .= "AppID for the Production environment.</h3>";
    }
    
    echo "<table>".$results."</table>";