Shealan
Shealan

Reputation: 1346

Problems reading an RSS feed with SimpleXML

I am trying to read a simple Twitpic rss feed but not having much luck. I can't see anything wrong with my code, but its only returning the following when using print_r()

Array ( [title] => SimpleXMLElement Object ( ) )

Here is my code:

function get_twitpics() {

    /* get raw feed */

    $url = 'http://www.twitpic.com/photos/Shealan/feed.rss'; 
    $raw = file_get_contents($url); 
    $xml = new SimpleXmlElement($raw);

    /* create array from feed items */

    foreach($xml->channel->item as $item) {

        $article = array();
        $article['title'] = $item->description;
    }

    return $article;
}

Upvotes: 2

Views: 468

Answers (3)

danlefree
danlefree

Reputation: 478

foreach($xml->channel->item as $item) {
    $article = array(); // so you want to erase the contents of $article with each iteration, eh?
    $article['title'] = $item->description;
}

You might want to look at your for loop if you're interested in more than just the last element - i.e.

$article = array();
foreach($xml->channel->item as $item) {
    $article[]['title'] = $item->description;
}

Upvotes: 4

bcosca
bcosca

Reputation: 17555

Typecast the following explicitly to (string):

$item -> title
$item -> link
$item -> description

Upvotes: 1

Tim Lytle
Tim Lytle

Reputation: 17624

If you want the data as a specific type, you'll need to explicitly type it:

foreach($xml->channel->item as $item) {

    $article = array();
    $article['title'] = (string) $item->description;
}

Upvotes: 3

Related Questions