2011-03-03 34 views
0

我需要通过PHP将新的item元素添加到我的RSS文件,而无需从PHP生成RSS。我知道这将需要删除旧的项目,以匹配我想要显示的数字,但我不知道如何将它们添加到文件中。将PHP添加到RSS文件中,而不通过PHP生成RSS

我的代码看起来有点像这样:

<rss version="2.0"> 
    <channel> 
    <title>My Site Feed</title> 
    <link>http://www.mysitethathasfeed.com/feed/</link> 
    <description> 
     A nice site that features a feed. 
    </description> 
    <item> 
     <title>Launched!</title> 
     <link>http://www.mysitethathasfeed.com/feed/view.php?ID=launched</link> 
     <description> 
      We just launched the site! Come join the celebration! 
     </description> 
    </item> 
    </channel> 
</rss> 
+0

你是什么意思“而不会产生RSS”是什么意思?听起来你需要解析现有的文档,操作它,然后重新生成并输出RSS。 – deceze 2011-03-03 02:38:43

+0

我的意思是访问时不会生成内容。 RSS需要时才添加,然后在访问RSS时不需要PHP处理。 – 2011-03-03 03:00:14

+0

@Tanner:我明白你要做什么 - 这是一个静态的RSS文件,它由PHP操作,然后作为静态文件重新存储,而不是通过执行PHP脚本随时随地创建的文件。你有任何理由采取这种方法吗?通过执行PHP脚本即时生成RSS输出是管理动态内容的更好方式。 – 2011-03-03 03:36:14

回答

0

扩展凯尔(哦OOP的传承)的答案,并引用来自PHP Manual

<?php 

$rss = file_get_contents('feed.rss'); 
$dom = new DOMDocument(); 
$dom->loadXML($rss); 

// should have only 1 node in the list 
$nodeList = $dom->getElementsByTagName('channel'); 

// assuming there's only 1 channel tag in the RSS file: 
$nChannel = $nodeList->item(0); 

// now create the new item 
$newNode = $dom->createElement('item'); 
$newNode->appendChild($dom->createElement('title', 'a new title post')); 
$newNode->appendChild($dom->createElement('link', 'http://www.mysitethathasfeed.com/feed/view.php?ID=launched')); 
$newNode->appendChild($dom->createElement('description', 'This is the 2nd post of our feed.')); 

// add item to channel 
$nChannel->appendChild($newNode); 
$rss = $dom->saveXML(); 
file_put_contents('feed.rss', $rss); 
1
// Load the XML/RSS from a file. 
$rss = file_get_cotents('path_to_file'); 
$dom = new DOMDocument(); 
$dom->loadXML($rss); 

使用http://php.net/manual/en/book.dom.php学习如何修改您所加载的DOM。