1

New to PHP and was just playing around with RSS feeds.

I'm currently just trying to display the RSS feed from here: http://www.polygon.com/rss/index.xml.

Bbut I think my code is broken somewhere and was hoping someone could shed some light on the issue.

This is the function I am using:

<?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);
}

?>

When loading the page no content is displaying :( All I get is this:

Array ( )

Any Ideas on what I am doing wrong? I'm guessing it has something to do with that foreach statement.

Thanks for any help :)

Kevin
  • 41,694
  • 12
  • 53
  • 70
StackUnderFlow
  • 339
  • 1
  • 11
  • 36

1 Answers1

1

First off, there is no ->channel->item inside $data. It's ->entry.

Second, you can gather the results in the container and then return the values gathered. Then invoke the function:

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

Kevin
  • 41,694
  • 12
  • 53
  • 70