繁体   English   中英

如何通过PHP显示XML RSS feed

[英]How to display XML RSS feed by PHP

我分配了一个网站,以通过PHP在XML上显示我的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显示此文件?

尝试使用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);
}

这是一个提示。 希望对您有帮助。

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

但是当我的代码是simplexml时,该代码将适用于DOM文件。 我用下面的代码解决了这个问题

    <?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>";
} 
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM