2012-05-14 45 views

回答

2

考虑到某些Feed结构不同,我没有明确的方式来做到这一点,我知道。这是我能够做到it.First看看这篇文章:

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; ?> 

这可能需要一些迷恋,但一旦你知道你的img标签的饲料中存在,就可以得到了SimplePie解析饲料和功能会发现标签和格式,所以它是HTML的准备。

如果只拉一个职位,你可以编辑你的循环:

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

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

+0

hmm.nice谢谢。 –

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上的文档以获取更多信息。

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