简体   繁体   中英

How to display XML RSS feed by PHP

I have an assignment to display my XML RSS via PHP on a website, so far I have tried multiple things and all have failed. And I was unable to find the answer since most people do RSS feed by PHP from MySQL database to get a live feed of posts.

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>

How can I display this file via PHP?

Try to use the DOMDocument() class, for example:

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

This is a tip. I hope I have helped you.

Thank you very much for leading me onto the right track!

But that code would work for DOM file while mine was simplexml. I used the following code to solve the problem

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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