How to display WordPress RSS feed your website?

To accomplish this you need to read the RSS of the blog, from RSS you need to read the Title and the description, after reading the whole description and title you need to trim the description to your desired number of letters. After that you need to check weather the description last word has been completed or not and then you need to remove a the last word if not completed and put the “…”.

First we will make a script to trim the description and to put “…” in last:-

<?php
global $text, $maxchar, $end;
function substrwords($text, $maxchar, $end='...') {
    if (strlen($text) > $maxchar || $text == '') {
        $words = preg_split('/\s/', $text);      
        $output = '';
        $i      = 0;
        while (1) {
            $length = strlen($output)+strlen($words[$i]);
            if ($length > $maxchar) {
                break;
            } 
            else {
                $output .= " " . $words[$i];
                ++$i;
            }
        }
        $output .= $end;
    } 
    else {
        $output = $text;
    }
    return $output;
}

Now we will define the variables in which we store the values:-

$xml=("http://your-blog-path/rss/");
global $item_title, $item_link, $item_description;

$xmlDoc = new DOMDocument();

$xmlDoc->load($xml);

$x=$xmlDoc->getElementsByTagName('item');

Now, we will make an array and store values in it. I am only taking 3 because you have asked it the way. You can change it to anything (The number of post you want to show, put that in the loop)

for ($i=0; $i<3; $i++)

{

$item_title[$i] = $x->item($i)->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;

$item_link[$i] = $x->item($i)->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;

$item_description[$i] = $x->item($i)->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;

}

?>

Now echo all these values, Link is the value where your user will click and he will be taken to your blog:-

FIRST RECENT POST:

<a href="<?php echo $item_link[0]; ?>"><?php echo $item_title[0]; ?></a>
<?php echo substrwords($item_description[0],70); ?>

SECOND RECENT POST:

<a href="<?php echo $item_link[1]; ?>"><?php echo $item_title[1]; ?></a>
<?php echo substrwords($item_description[1],70); ?>

THIRD RECENT POST:

<a href="<?php echo $item_link[2]; ?>"><?php echo $item_title[2]; ?></a>
<?php echo substrwords($item_description[2],70); ?>

Hope this can solve your problem. By the way Nice question.

Leave a Comment