2013-01-07 33 views
0

我使用simplexml_load_file从wordpress博客获取rss订阅源。这里是我的代码simplexml_load_file从WP订阅源重复生成相同的帖子

$rssfile = simplexml_load_file("http://blog.sufuraamathi.com/?feed=rss2"); 
$items = $rssfile->channel->item ; 

foreach($items as $item) { 
    $article = array(); 
    $article['title'] = $item->title; 
    $article['link'] = $item->link; 
    $article['category'] = $item->category; 
} 

foreach($items as $item) { ?> 
<?php if($article['category']=="Uncategorized") { ?> 

    <div><?php echo $article['title'];?></div> 
<?php 
} } ; 

?> 

的问题:它重复输出同一职位x次,其中x是职位的总数。目前,Uncategorized类别中只有两个帖子,其他类别中有三个帖子。但代码回声如下:

<div>Hello world!</div> 
<div>Hello world!</div> 
<div>Hello world!</div> 
<div>Hello world!</div> 
<div>Hello world!</div> 

回答

0

您的问题是您的发布代码的第五行。作为当前解决方案重置$article阵列的每一行

$rssfile = simplexml_load_file("http://blog.sufuraamathi.com/?feed=rss2"); 
$items = $rssfile->channel->item ; 

$article = array(); // <- put it here 
foreach($items as $item) { 
    $article['title'] = $item->title; 
    $article['link'] = $item->link; 
    $article['category'] = $item->category; 
} 
... 

:你必须拿出第一foreach循环的数组定义。但是,为什么你不把所有的东西都放在一个foreach循环中呢?如果您没有将$article用于其他目的,我没有看到使用将$item数据分配给阵列。代码可以简化:

$rssfile = simplexml_load_file("http://blog.sufuraamathi.com/?feed=rss2"); 
$items = $rssfile->channel->item ; 

foreach($items as $item) { ?> 
<?php if($item->category=="Uncategorized") { ?> 
    <div><?php echo $item->title;?></div> 
<?php 
} } ?>