PHP RSS Feed没有显示

时间:2014-11-17 00:54:41

标签: php xml rss simplexml

PHP的新手,只是在玩RSS源。

我目前只是想从这里显示RSS源:http://www.polygon.com/rss/index.xml

Bbut我认为我的代码在某处被破坏了,希望有人可以对这个问题有所了解。

这是我正在使用的功能:

<?php

function fetch_news(){
    $data = file_get_contents('http://www.polygon.com/rss/index.xml');
    $data = simplexml_load_string($data);

    $articles = array();

    foreach ($data->channel->item as $item){
        $articles[] = array(
            'title'     => (string)$item->title,
            'content'   => (string)$item->content,
            'href'      => (string)$item->href,
            'published' => (string)$item->published,
            );
    }

    print_r($articles);
}

?>

加载页面时没有显示任何内容:(我得到的就是:

  

Array()

关于我做错了什么的任何想法?我猜这与foreach声明有关。

感谢您的帮助:)

1 个答案:

答案 0 :(得分:1)

首先,->channel->item内没有$data。这是->entry

其次,您可以在容器中收集结果,然后返回收集的值。然后调用函数:

function fetch_news(){
    $articles = array();
    $data = simplexml_load_file('http://www.polygon.com/rss/index.xml');
    foreach ($data->entry as $entry){
        $articles[] = array(
            'title'     => (string) $entry->title,
            'content'   => (string) $entry->content,
            'href'      => (string) $entry->href,
            'published' => (string) $entry->published,
        );
    }

    return $articles;
}

$news = fetch_news();
echo '<pre>';
print_r($news);

Sample Output