Getting image url from RSS feed using simplepie
Asked Answered
S

1

5

I am very new to php and simplepie. I would like to be able to use simplepie to store an image url to a variable. For my example, I will use the ebay rss feed (http://deals.ebay.com/feeds/rss). The image that I am trying to get the url of is in a <image src= tag. When i use the code

foreach ($feed->get_items() as $item):
?>
<?php echo $item->get_description(); ?>
<?php endforeach; ?>

The image and description are shown, but I am unable to store the image url to a variable. How can I use simplepie to store an image url to a variable?

Thanks

Sixgun answered 25/3, 2012 at 23:55 Comment(0)
M
8

You can use DOM parser such as SimpleHTML like:

require_once('simple_html_dom.php');

foreach ($feed->get_items() as $item)
{
 $description =  $item->get_description();
 $desc_dom = str_get_html($description);
 $image = $desc_dom->find('img', 0);
 $image_url = $image->src;
}

It returns the URL of first image. If you want to get all images, you can store them in array like $desc_dom->find('img');

If you are using SimpleHTML on composer projects, use

composer require mgargano/simplehtmldom
Mordent answered 26/3, 2012 at 0:7 Comment(13)
But is it a good idea to use both simple pie and DOM parser at the same time?Sixgun
I think, there is no problem.Mordent
The code does work, but the page loads much slower. Is there a way to only use SimplePie and not SimpleHTML?Sixgun
actually I haven't used SimplePie, but generally you can write function for getting image with regular expression too.Mordent
but I would prefer to use DOM parser instead of regexMordent
Would you reccomend stop using simplepie and only using a DOM parser?Sixgun
Also how can I view the url of the image, not the image itself?Sixgun
since I haven't used SimplePie, I can't say anything. but in principle, it is possible parsing rss feed with DOM parser like SimpleHTMLMordent
foreach ($image_url as $element){ echo $element->src; }Mordent
if $image_url is not an array, I mean $image_url = $desc_dom->find('img', 0); then just use $image_url->srcMordent
Great thank you very much. The one last thing I liked about simplepie was the cache feature, so simplepie would only check for new rss posts every 30 mins. Is there a way to do this using DOM parser?Sixgun
You're welcome. You can do this with cron feature of Linux.Mordent
Couldn't find this anywhere else. I was making my project which is due tomorrow and I just login to upvote your answer. You sir are awesome! @ValehHajiyevNatant

© 2022 - 2024 — McMap. All rights reserved.