user1053263
user1053263

Reputation: 742

PHP: foreach not forming an array

I do this and it works.

<?php
    function load_file($url) 
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $xml = simplexml_load_string(curl_exec($ch));
        return $xml;
    }

    $feedurl = 'http://www.astrology.com/horoscopes/daily-extended.rss';
    $rss = load_file($feedurl);

    $items = array();
    $count = 0;
    foreach ($rss->channel->item->description as $i => $description) 
    {
        $items[$count++] = $description;
    }
    echo $items[0];
?>

When I echo $items[1]; it doesn't show the next one in line. Not sure what I did wrong.

Upvotes: 0

Views: 363

Answers (1)

Thomas Clayson
Thomas Clayson

Reputation: 29935

Here is an example of your xml:

<channel>
    <item>
        <description>blah</description>
    </item>
    <item>
        <description>blah1</description>
    </item>
    <item>
        <description>blah2</description>
    </item>
    <item>
        <description>blah3</description>
    </item>
</channel>

When you do $rss->channel->item->description you're getting the first item's description.

You need to first loop through the items and then get each description.

e.g.:

$descriptions = array();
foreach($rss->channel->item as $item){
    $descriptions[] = $item->description;
    // note I don't need the $count variable... if you just use
    // [] then it auto increments the array count for you.
}

Hope that helps. Its untested, but should work.

Upvotes: 4

Related Questions