Reputation: 856
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.
Upvotes: 0
Views: 77
Reputation: 24549
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());
}
Upvotes: 1