2013-01-07 37 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 
} } ?>