用php在网页中查看rss feed?

时间:2014-06-30 17:33:05

标签: php wordpress web rss

我正在尝试查看我的网站rss在不同页面的侧边栏中提供。我猜我应该使用PHP,但我不是100%肯定。这是包含RSS Feed http://unleashedinteractivestudios.pcriot.com/feed/的页面,这是带有侧栏http://unleashedinteractivestudios.pcriot.com/的页面 这是我边栏的代码:

<div class='sidebar'> RSS FEED</div>

编辑:

我添加了此代码,但它只显示了没有帖子的错误日期。

<?php
  $rss = new DOMDocument();
  $rss->load('unleashedinteractivestudios.pcriot.com/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>';
  }

看看它here,看看我的意思。

2 个答案:

答案 0 :(得分:1)

或者,您也可以使用SimpleXMLElement。考虑这个例子:

$data = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://unleashedinteractivestudios.pcriot.com/feed'); // put the correct full url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$raw_rss = curl_exec($ch);
$rss = new SimpleXMLElement($raw_rss);

foreach($rss->channel as $entry) {

    // if you also want the namespaces
    $namespaces = $entry->getNamespaces(true);
    $sy = $entry->children($namespaces['sy']);

    $data[] = array(
        'title' => (string) $entry->title,
        'link' => (string) $entry->link,
        'description' => (string) $entry->description,
        'lastBuildDate' => (string) $entry->lastBuildDate,
        'language' => (string) $entry->language,
        'generator' => (string) $entry->generator,
        'sy:updatePeriod' => (string) $sy->updatePeriod,
        'sy:updateFrequency' => (string) $sy->updateFrequency,
    );

}

echo '<pre>';
print_r($data);

应该产生类似的东西:

Array
(
    [0] => Array
        (
            [title] => Unleashed Interactive Studios » Page not found
            [link] => http://unleashedinteractivestudios.pcriot.com
            [description] => The Cooler Side of Coding
            [lastBuildDate] => Mon, 30 Jun 2014 21:16:17 +0000
            [language] => en-US
            [generator] => http://wordpress.org/?v=3.9.1
            [sy:updatePeriod] => hourly
            [sy:updateFrequency] => 1
        )

)

答案 1 :(得分:0)

您看过here还是here?它们都包含用PHP显示RSS源的方法。