使用rss feed仅显示simplepie中的图像

时间:2012-05-14 05:05:14

标签: image simplepie

如何在使用rss feed时只显示simplepie中的图像。我正在使用simplepie但只能从rs中提取图像。如何做到这一点?

2 个答案:

答案 0 :(得分:2)

考虑到某些饲料结构不同,我所知道的并没有明确的方法。这就是我能够做到的。首先看看这篇文章:

How to Display Thumbnail from WordPress RSS feed using SimplePie?

我能够复制并粘贴代码并进行一些小改动

我没有使用Wordpress,但它帮助我了解了需要做什么。

在feed-> init();

之后插入此代码
    //This function will get an image from the feed

function returnImage ($text) {
    $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
    $pattern = "/<img[^>]+\>/i";
    preg_match($pattern, $text, $matches);
    $text = $matches[0];
    return $text;
}


    //This function will filter out image url which we got from previous returnImage() function

    function scrapeImage($text) {
        $pattern = '/src=[\'"]?([^\'" >]+)[\'" >]/';
        preg_match($pattern, $text, $link);
        $link = $link[1];
        $link = urldecode($link);
        return $link;

    }

现在你要调用这些函数,以便搜索描述,或者在我的情况下搜索内容,以找到img标记并正确地构造输出。这就是我的代码:

foreach ($feed->get_items(0 , 3) as $item):
    $feedDescription = $item->get_content();
    $image = returnImage($feedDescription);
    $image = scrapeImage($image);
    $image_url= $item->get_permalink();
    $description = $item->get_description();
?>
        <div class="item">
            <h4><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h4>
            <div class="image-box"><?php echo '<a href="' . $image_url . '"><img src="' . $image . '" /></a>'."\n";?></div>
            <p><?php echo $description ?></p>
            <p><a href="<?php echo $item->get_permalink(); ?>">Continue Reading</a></p>   
        </div>

    <?php endforeach; ?>

可能需要一些buggin,但是一旦你知道你的img标签在feed中的位置,就可以使用simplepie来解析feed,函数会找到标签和格式,这样它就可以了。

要只拉一个帖子,你可以编辑你的循环:

foreach ($feed->get_items(0 , 1) as $item): 

第一个数字(0)是起点,0是最新的帖子。第二个数字(1)是要拉多少个帖子。由于您只需要一个图像,因此您希望该数字为1.

答案 1 :(得分:1)

也许您想在客户端进行此操作。然后用jQuery很容易。 假设您的javascript中的项目内容看起来像这样

var content = '<div><a href="http://kwout.com/cutout/b/es/y2/ukn_rou_sha.jpg"
imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;">
<img border="0" height="239" src="http://kwout.com/cutout/b/es/y2/ukn_rou_sha.jpg"
width="320"></a>Erat austro rerum.</div>';

然后,您可以使用jQuery选择器轻松识别和隔离内容中的图像。例如使用

$(content).find('img:first');   //find the FIRST image inside an element or
$(content).find('a:first');     //take the hyperlink AND the image

如果它不是内容中的第一个图像,或者内容比这个例子更复杂(主要是;-) - 不用担心 - 那么其他一些选择器就可以了。请查看jquery.com上的文档以获取更多信息。

这样我删除了元素,在内容中的不同元素中添加了一些或添加的类,以便按照我的方式显示帖子。

相关问题