Skip to content
Advertisement

How can I append RSS data to the existing RSS XML file?

I have an RSS data XML file existing on the folder. I have to append new data to the RSS XML file. I need to do it with PHP only. I have rss data (item, title, url, desc) coming from web service. I have to append to the existing rss xml file which has previous data.

RSS data format is like this

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

I want to add another item dynamically a using PHP only. How can I do that?

Advertisement

Answer

Have a look at: Document Object Model

And here is something, which might get you started:

$dom = new DOMDocument;
$dom->load('%path-to-your-rss-file%');

$xpath = new DOMXPath($dom);
$channelNode = $xpath->query('/rss/channel')->item(0);
if ($channelNode instanceof DOMNode) {
    // create example item node (this could be in a loop or something)
    $item = $channelNode->appendChild($dom->createElement('item'));

    // the title
    $item->appendChild(
        $dom->createElement('titel', '%title text%')
    );
    
    // the link
    $item->appendChild(
        $dom->createElement('link', '%link text%')
    );
    
    // the description
    $item->appendChild(
        $dom->createElement('description', '%description text%')
    );
}

$dom->save('%path-to-your-rss-file%');

You’ll need write-access to the xml file, of course!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement