如何通过PHP显示XML RSS提要

时间:2017-07-04 00:13:22

标签: php xml rss

我有一个在网站上通过PHP显示我的XML RSS的任务,到目前为止,我已尝试了多项内容,但都失败了。我无法找到答案,因为大多数人都是通过PHP从MySQL数据库进行RSS提要来获得帖子的实时提要。

XML RSS

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

<channel>
  <title>Treehouse front page</title>
  <link>https://teamtreehouse.com/</link>
  <description>Programming Tutorials</description>
  <item>
    <title>Code Academy</title>
  <link>https://teamtreehouse.com/</link>
  <description>Programming Tutorials</description>
  </item>
</channel>

</rss>

如何通过PHP显示此文件?

2 个答案:

答案 0 :(得分:2)

尝试使用DOMDocument()类,例如:

$rss = new DOMDocument();
$rss->load("http://yoursite.com/rss/");

$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);
}

这是一个提示。我希望我能帮到你。

答案 1 :(得分:2)

非常感谢您带领我走上正轨!

但是该代码适用于DOM文件,而我的是simplexml。 我使用以下代码来解决问题

    <?php
$rss = simplexml_load_file('rss.xml');

echo '<h4>'. $rss->channel->title . '</h4>';

foreach ($rss->channel->item as $item) {
   echo '<h4><a href="'. $item->link .'">' . $item->title . "</a></h4>";
   echo "<p>" . $item->title . "</p>";
   echo "<p>" . $item->description . "</p>";
} 
?>