0

I found this code for displaying wordpress posts on my page from an RSS feed. However it has a limit to display only 5 posts.

<?php
    $rss = new DOMDocument();
    $rss->load('http://wordpress.org/news/feed/');
    $feed = array();
    foreach ($rss->getElementsByTagName('item') as $node) {
        $item = array ( 
            'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
            'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
            'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
            'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
            );
        array_push($feed, $item);
    }
    $limit = 5;
    for($x=0;$x<$limit;$x++) {
        $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
        $link = $feed[$x]['link'];
        $description = $feed[$x]['desc'];
        $date = date('l F d, Y', strtotime($feed[$x]['date']));
        echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />';
        echo '<small><em>Posted on '.$date.'</em></small></p>';
        echo '<p>'.$description.'</p>';
    }
?>

I could just increase the $limit to "50" for example but if I have less that 50 posts it will show me an error.

My guess would be to strip out these lines but it seems to stop the script functioning:

$limit = 5;
for($x=0;$x<$limit;$x++)
4

4 回答 4

3

同时

$limit = count($feed);

行得通,它还可能导致显示大量文章。

你可以试试

$count = count($feed);
$limit = $count > 50 ? 50 : $count;

如果有更多,这会将其限制为 50

于 2013-07-15T09:27:47.013 回答
2

这应该做。您基本上将其限制为提要中包含的所有项目。

$limit = count($feed);

我也会把它包起来,if以确保它有物品。

$limit = count($feed);
if ($limit > 0)
{
    for($x=0;$x<$limit;$x++) {
        $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
        $link = $feed[$x]['link'];
        $description = $feed[$x]['desc'];
        $date = date('l F d, Y', strtotime($feed[$x]['date']));
        echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />';
        echo '<small><em>Posted on '.$date.'</em></small></p>';
        echo '<p>'.$description.'</p>';
    }
}
于 2013-07-15T09:24:43.033 回答
1

您可以使用count()以下方式计算数组中的元素数:

$limit = count($feed); //store number of elements

if ($limit > 0) { //checking if at least one element exists

    for($x=0; $x<$limit ;$x++) { 
    $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
    $link = $feed[$x]['link'];
    $description = $feed[$x]['desc'];
    $date = date('l F d, Y', strtotime($feed[$x]['date']));
    echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />';
    echo '<small><em>Posted on '.$date.'</em></small></p>';
    echo '<p>'.$description.'</p>';
    }

}

希望这可以帮助!

于 2013-07-15T09:28:39.263 回答
1

用作来limitfeed

$limit = count($feed);
于 2013-07-15T09:25:32.137 回答