问题
I'm trying to create an array of items from an RSS feed. I'm trying to test if it's working by echoing the title of the first item. I've been unsuccessful so far...I'd really appreciate any advice!
I have two files, an 'index.php' and a 'test.php'.
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type= "text/css" href = "style.css">
</head>
<body>
<h1>TEST SLIDER</h1>
<p>First Title:<br>
<?php
include 'test.php';
$NPR_url = 'http://www.npr.org/rss/rss.php?id=1001';
$NPR = GetFeed($NPR_url);
echo $NPR[0]['title'];
?>
</p>
</body>
</html>
and 'test.php'
<?php
function GetFeed($url){
$feed = new DOMDocument;
$feed->load($url);
$feed_array = array();
foreach($feed->getElementsByTagName('item') as $story){
$story_array = array (
'title' => $story->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $story->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $story->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $story->getElementsByTagName('pubDate')->item(0)->nodeValue
);
array_push($feed_array, $story_array);
}
return $feed_array;
}
?>
回答1:
DOMDocument could not get the 'channel' object after parsing. Here's the GetFeed() function using simpleXML:
test.php
<?php
function GetFeed($url){
$feed = simplexml_load_file($url);
$feed_array = array();
foreach($feed->channel->item as $story){
$story_array = array (
'title' => $story->title,
'desc' => $story->description,
'link' => $story->link,
'date' => $story->date
);
array_push($feed_array, $story_array);
}
return $feed_array;
}
?>
Hope it helps. Your index.php will remain same.
回答2:
Try this ::
<?php
$rss = new DOMDocument();
$rss->load($url);
$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(' & ', ' & ', $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>';
}
?>
Edit : If you are looking for more advanced way, you can use this awesome class by David Grudl.
来源:https://stackoverflow.com/questions/18906366/parsing-an-rss-feed-in-php-with-dom