0

I am using simplepie to get some feeds, I have set the key in the array which I am having trouble accessing. Here's my code:

$feed->set_feed_url(array(
    'Title One'=>'http://example.com/rss/index.xml',
    'Title Two'=>'http://feeds.example.com/rss/example',
    'Title Three'=>'http://feeds.example.com/ex/blog'
));

When I loop over and try to access it I'm getting errors, here's how I am trying to access it.

foreach ($feed->get_items() as $item):
echo $item[0];

Fatal error: Cannot use object of type SimplePie_Item as array

How can I access those I tried also:

echo $item->[0];

without luck.

2
  • Please do a print_r($feed) and post the output. Commented Dec 24, 2015 at 14:41
  • @JosephGarrone Output is very big, you can view it here pastebin.com/iG5tQuh9 Commented Dec 24, 2015 at 14:53

1 Answer 1

1

When you loop over an array (often used with associative arrays) using foreach, there is an additional construct to be able to get the key. It looks like this:

foreach ($feed->get_items() as $key => $item) {
   echo($key);
}

So an array with a structure like:

$myArray = [
   'a' => 1,
   'b' => 2,
];

When iterated with foreach in that syntax, will put "a" or "b" in the $key variable depending on which iteration it is, and $item will contain either "1" or "2".

In your case, $item is the object instance and then you are trying to access it like it is an array. If you need to know the key, use that other foreach syntax.

To get the title of the SimplePie_Item object, you can call get_title():

foreach ($feed->get_items() as $index => $item) {
   echo($item->get_title());
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, in my case it's returning 0,1,2,3,4,5,6 etc and not the set key. Why's this?
What value are you expecting? "Title One"?
When you call set_feed_url() you are passing that data in, but that is not what get_items returns as a response. Looking briefly at the documentation, it looks like you need to call $item->get_title()
Yes you're right Jeremy, however there are feeds that don't supply titles, or have very long titles, which is causing issues at the moment. Anyway to access or set the title?
The full list of methods available for the SimplePie_Item class are at simplepie.org/wiki/reference/simplepie_item/start

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.