Search code examples
phpif-statementsimplepie

php if statement to display remove thumbnail


I'm trying to use an if statement so that if the variable isn't set it wil display "noimg.jpg" or no thumbnail, but it isn't doing that at the moment, it's displaying a broken thumbnail.

$feed = new SimplePie_random_sort();

$feed->set_feed_url(array(

    'http://www.thelocal.de/feeds/rss.php',
    'http://dailymail.co.uk',
    'http://www.exberliner.com/',
    'http://www.telegraph.co.uk/news/worldnews/europe/germany/',
));


$feed->set_item_limit(3);
//enable caching
$feed->enable_cache(true);

//provide the caching folder
$feed->set_cache_location('cache');

//set the amount of seconds you want to cache the feed
$feed->set_cache_duration(1800);

//init the process
$feed->init();

//let simplepie handle the content type (atom, RSS...)
$feed->handle_content_type();

<?php foreach ($feed->get_items() as $item): ?>
<?php if ($enclosure = $item->get_enclosure())
    {
    echo '<img src="' . $enclosure->get_link() . '" class="feed-thumb" />';
    }
    else echo'<img src="noimg.jpg">';
    ?>
    <?php endforeach; ?>

the results from the var_dump: object(SimplePie_Enclosure)#399 (27) { ["bitrate"]=> NULL ["captions"]=> NULL ["categories"]=> NULL ["channels"]=> NULL ["copyright"]=> NULL ["credits"]=> NULL ["description"]=> NULL ["duration"]=> NULL ["expression"]=> NULL ["framerate"]=> NULL ["handler"]=> NULL ["hashes"]=> NULL ["height"]=> NULL ["javascript"]=> NULL ["keywords"]=> NULL ["lang"]=> NULL ["length"]=> NULL ["link"]=> NULL ["medium"]=> NULL ["player"]=> NULL ["ratings"]=> NULL ["restrictions"]=> array(1) { [0]=> object(SimplePie_Restriction)#220 (3) { ["relationship"]=> string(5) "allow" ["type"]=> NULL ["value"]=> string(7) "default" } } ["samplingrate"]=> NULL ["thumbnails"]=> NULL ["title"]=> NULL ["type"]=> NULL ["width"]=> NULL } I'm not sure how to amend the if statement based on this info?


Solution

  • You have an assignment inside your if

    if ($enclosure = $item->get_enclosure())
    

    This assignment is evaluated to the value you are assigning to $enclosure. If that value is truey, then the condition evaluates to true. Otherwise, it will evaluate to false. The problem is that in some cases you expect it to evaluate as false, but it evaluates as true. The solution is to refine your conditional to evaluate the right condition and make sure you do not forget the value assignment. It is not a bad idea to put a var_dump($enclosure) inside the block represented as curly brackets and reproduce the issue. What is dumped? An object? How is it truey? Take the info you have gathered this way and fix the conditional.