-->

Get youtube thumbnail simplepie

2019-02-21 00:27发布

问题:

So I'm trying to get a thumbnail of a youtube video in simple pie, my problem is that the get_thumbnail() function doesn't seem to be pulling it because the get_enclosure function seems to be returning no values.

Is there something that must be done to initialize the simplepie object to get the enclosure properly?

回答1:

Not all feeds support/use RSS enclosures it isn't part of the RSS standard at least not the original RSS standard. It is part of something called MediaRSS. None the less this can be done. Another problem is Google has been changing GData API which is what actually makes the RSS feeds for YouTube or it did, you might want to use this API instead which produces Atom feeds. You probably want to look at some documentation.

You have to use additional code beyond SimplePie to create a thumbnail for some feeds, I used something called simple_html_dom and another script called thumbnail.php to make thumbnails as necessary. Your life is better if your have a feed like Flickr which supports MediaRSS but if you gotta force the creation of a thumbnail, I used this code:

if ($enclosure = $item->get_enclosure())
{
// Check to see if we have a thumbnail.  We need it because this is going to display an image.
    if ($thumb = $enclosure->get_thumbnail())
{
    // Add each item: item title, linked back to the original posting, with a tooltip containing the description.
    $html .= '<li class="' . $item_classname . '">';
    $html .= '<a href="' . $item->get_permalink() . '" title="' . $title_attr . '">'; 
    $html .= '<img src="' . $thumb . '" alt="' . $item->get_title() . '" border="0" />';
    $html .= '</a>';
    $html .= '</li>' . "\n";
}
}
else
{
// There are feeds that don't use enclosures that none the less are desireable to dsipaly wide as they contain primarily images
// Dakka Dakka and some YouTube feeds fall into this category, not sure what is up with Chest of Colors...
$htmlDOM = new simple_html_dom();
$htmlDOM->load($item->get_content());

$image = $htmlDOM->find('img', 0);
$link = $htmlDOM->find('a', 0); 

// Add each item: item title, linked back to the original posting, with a tooltip containing the description.
$html .= '<li class="' . $item_classname . '">';
$html .= '<a href="' . $link->href . '" title="' . $title_attr . '">'; 
// Sometimes I'm not getting thumbnails, so I'm going to try to make them on the fly using this tutorial:
// http://www.webgeekly.com/tutorials/php/how-to-create-an-image-thumbnail-on-the-fly-using-php/
$html .= '<img src="thumbnail.php?file=' . $image->src . '&maxw=100&maxh=150" alt="' . $item->get_title() . '" border="0" />';
$html .= '</a>';
$html .= '</li>' . "\n";
}

The formatting seems a bit odd, but that is ripped right from my code which is running here. You're still best off not making a lot of thumbnails from a feed that doesn't support them.