PHP添加到RSS文件,而不通过PHP生成RSS

时间:2011-03-03 02:34:47

标签: php xml

我需要通过PHP在我的RSS文件中添加一个新的item元素,而不需要从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>

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分:0)

扩展Kyle(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);