Thursday 25 April 2013

Fetch RSS feed data in PHP

Create a file named "rssfeed.php" and copy paste the following code.
Try "http://www.aweber.com/blog/feed/" link which is containing link title and images.
See the Demo here: http://creativeideate.net23.net/demos/rssfeed/rssindex.php

⇛ HTML Code: Input field to enter rss feed

<form action="rssfeed.php" method="POST">
    <input type="text" name="feedurl"/>                    
    <input type="submit" name="submit" value="GO"/>
</form>

⇛ PHP code and tabular listing of feed data

<?php
error_reporting(E_ERROR);
if (isset($_POST['feedurl'])):
    $content = file_get_contents($_POST['feedurl']);
    try {
        $rss = new SimpleXmlElement($content);
    } catch (Exception $e) {
        return false;
    }
    $rssdata = array();
    $i = 0;

    foreach ($rss->channel->item as $item) :
        $title = (string) $item->title;
        $link = (string) $item->link;
        $content = $item->children('content', true)->encoded;
        preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $content, $image);
        $image = substr($image['src'], 0, strpos($image['src'], '"'));
        $rssdata[$i]['title'] = $title;
        $rssdata[$i]['link'] = $link;
        $rssdata[$i]['image'] = $image;
        $i++;
    endforeach;
    ?>

    <!-- TABULAR LISTING -->

    <table border="1">
        <th>Image</th>
        <th>Title</th>        

        <?php foreach ($rssdata as $feed): ?>
            <tr>
                <td><img src="<?php echo $feed['image']; ?>" height="100" width="200"/></td>
                <td><a href="<?php echo $feed['link']; ?>"><?php echo $feed['title']; ?></a></td>                
            </tr>
        <?php endforeach; ?>
    </table>

    <?php
endif;
?>

No comments:

Post a Comment