简体   繁体   中英

parse image from rss feed

This is the code i have right now. I'm trying to grab the image of this site but the variable returns nothing meaning i can't grab it ive been looking for hours

$html = "";

 $url = "https://www.idownloadblog.com/tag/jailbreak/rss";
 $xml = simplexml_load_file($url);
 for($i = 0; $i < 1; $i++){

$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$description = $xml->channel->item[$i]->description;
$pubDate = $xml->channel->item[$i]->pubDate;
$image= $xml->channel->item[$i]->content;


$box1 .= "<a><b>$title</b></a>"; 
$dbox1 .= "$description"; 



}

Looking at the RSS feed you provided, it does not appear there is a site image. So if you want the site's logo, you may have to statically link that.

If you are wanting to get the post's image, we can do that. Here's what I would do.

I created a package to make xml parsing a breeze. You can find it here: https://github.com/mtownsend5512/xml-to-array

Then do the following:

$xml = \Mtownsend\XmlToArray\XmlToArray::convert(file_get_contents('https://www.idownloadblog.com/tag/jailbreak/feed/'));

Now you have a nice php array of the rss feed.

Next, we will create a helper function to get the first image out of the post's body. We'll use this as the post's featured image.

function getPostImage($content)
{
    $output = preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $matches);
    if (empty($matches[1][0])) {
        return 'http://yoursite.com/images/fallback-image.jpg';
    }
    return $matches[1][0];
}

You'll want to replace http://yoursite.com/images/fallback-image.jpg with the url to your fallback image if there is no image in the post.

Now, we loop through the posts:

foreach ($xml['channel']['item'] as $post) {
    $title = $post['title']);
    $link = $post['link'];
    $description = $post['description'];
    $pubDate = $post['pubDate'];
    $image = getPostImage($post["content:encoded"]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM