doujiaozhan2413 2014-06-16 07:41
浏览 49
已采纳

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

I only see bulleted list on a page when loading this script to read RSS feeds. What am I not doing right?

<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条回答 默认 最新

  • drgovyk64676 2014-06-16 07:56
    关注

    First off, you are not calling the proper rss url. That is just the homepage of the RSS feeds. You need to select one first. In this example, Top Stories is selected. Consider this example:

    <?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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?