问题
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?
回答1:
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>";
}
?>
回答2:
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.
来源:https://stackoverflow.com/questions/44895254/how-to-display-xml-rss-feed-by-php