phploopsconditional-statementssimplepie

conditional loop to fetch images in php simplepie rss


I am trying to make a news reader using SimplePie in PHP. Everything was working fine when i tried to fetch images from feeds. In my little understanding what i concluded is i have to fetch images in any of the following three ways.

1) fetch images Using $item->get_enclosure() with the following code:

<?php

    //Find Images from $item->get_enclosure()
    if ($enclosure = $item->get_enclosure()){
        $imageLink = $enclosure->get_link();
        if($imageLink !== "//?#") {
            echo "<a href=\"" . $item->get_permalink() . "\"><img src=\"$imageLink\"></a>";
            $imageLink = null;
        }
    }

?>

2) If there is no images, Then i have to fetch using $item->get_content() with following code:

    // Search for Images in $item->get_content() using str_img_src()
    if ($iurl = str_img_src($item->get_content())) {
        echo "<a href=\"" . $item->get_permalink() . "\"><img src=\"$iurl\"></a>";              
    }

?>

3) if i failed in that too, i should fetch from post permalink as follows:

<?php
    if ($imageLink === "//?#" && !$iurl) {
        // echo "Mandan<br>";
        $html = file_get_contents($item->get_permalink());

        $doc = new DOMDocument();
        @$doc->loadHTML($html);

        $tags = $doc->getElementsByTagName('img');

        foreach ($tags as $tag) {
                $imgUrl = "http://" . $tag->getAttribute('src');
                echo "<div style=\"float: left;\"></div><a href=\"" . $imgUrl . "\"><img src=\"" . $imgUrl . "\"></a><br>";
        }
    }
?>

My problem is i donno how to get image from only one method. if i succeeded in First Method, Then i should skip the 2nd and 3rd. if failed in first, then should check if possible with 2nd method and if it suceeds my program should skip 3rd method. and finally if 1st and 2nd fails, it should fetch images with 3rd method.

I tried with if and ifelse loops and not succeeded. How can i create a loop to do this without breaking others?

Sorry for my long elaborated question. donno how to make it short.


Solution

  • Like @devon said, I tried with else if and it did my job. Instead of checking each image availability in seperate if loops, i looped through if elseif loops. So only one result is generated and if any image is retrieved, then the loop stops and break out