使用' simplexml_load_file()'时只显示项目符号列表在PHP中阅读RSS源

时间:2014-06-16 07:41:52

标签: php mysql rss simplexml

在加载此脚本以阅读RSS源时,我只在页面上看到项目符号列表。我做得不对劲?

<html>
<head>
<title>RSS Feed Test</title>
</head>
<body>
<?php
    function fetchFeeds($url){
    $feed = simplexml_load_file($url);
    echo "<ul>";
    foreach($feed->channel->item as $itementry){
    echo "<li><a href='$itementry->link' title='$itementry->title'.$itementry->title"."</a></li>";
    }
    echo "</ul>";
    }
    echo fetchFeeds("http://rss.cnn.com/rss/cnn_topstories.rss");
    ?>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

首先,你没有调用正确的rss网址。这只是RSS提要的主页。您需要先选择一个。在此示例中,选择了热门故事。考虑这个例子:

<?php

// top stories RSS
$rss_url = 'http://rss.cnn.com/rss/edition.rss';
$xml = simplexml_load_file($rss_url);
$title = (string) $xml->channel->title; // typecast the title
$items = array();
for($i = 0, $size = count($xml->channel->item); $i < $size; $i++) {
    // also one way to extract is to convert it to this
    // each item will become an array
    $items[] = json_decode(json_encode($xml->channel->item[$i]), true);
}

?>

<!-- just plain foreach loop -->
<h1><?php echo $title; ?></h1>

<?php foreach($items as $key => $value): ?>
<ul>
    <li><?php echo $value['title']; ?></li>
    <li><a href="<?php echo $value['link']; ?>"><?php echo $value['link']; ?></a></li>
    <li><?php echo $value['description']; ?></li>
    <li><?php echo $value['pubDate']; ?></li>
</ul>
<br/>
<?php endforeach; ?>

Sample Output