Forum Moderators: coopster

Message Too Old, No Replies

Adding to existing XML file with DOM

DOM on server running php 5.04

         

sneaks

2:52 pm on Aug 30, 2005 (gmt 0)

10+ Year Member



i am having issue using DOM to insert a very simple news item to an xml file which follows the structure below. It appends to the end of the file and I would like to have the news <item> and its child data append within the <news> tag
Thanks!
j. :)

------------------------------------

<xml version="1.0">
<news>
<item>
<date>19720502</date>
<title>Title</title>
</item>
</news>

------------------------------------

<?php
$doc = new DOMDocument;
$doc->load('news/newsIndex.xml');
$doc->formatOutput = true;

$NewsItem = $doc->createElement('Item');
$NewsItem = $doc->appendChild($NewsItem);

$NewsDate = $doc->createElement('Date');
$NewsDate = $NewsItem->appendChild($NewsDate);

$DateValue = $doc->createTextNode('19720502');
$DateValue = $NewsDate->appendChild($DateValue);

$NewsTitle = $doc->createElement('Title');
$NewsTitle = $NewsItem->appendChild($NewsTitle);

$TitleValue = $doc->createTextNode('Test Title');
$TitleValue = $NewsTitle->appendChild($TitleValue);

$test = $doc->save("news/newstest.xml");
print 'done.';
?>

coopster

1:08 am on Sep 1, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You need to append your new item to the "news" node.

<?php 
$doc = new DOMDocument;
$doc->load('news/newsIndex.xml');
$doc->formatOutput = true;

$news = $doc->createElement('news');
$news = $doc->appendChild($news);

$NewsItem = $doc->createElement('item');
$NewsItem = $news->appendChild($NewsItem);

$NewsDate = $doc->createElement('Date');
$NewsDate = $NewsItem->appendChild($NewsDate);

$DateValue = $doc->createTextNode('19720502');
$DateValue = $NewsDate->appendChild($DateValue);

$NewsTitle = $doc->createElement('Title');
$NewsTitle = $NewsItem->appendChild($NewsTitle);

$TitleValue = $doc->createTextNode('Test Title');
$TitleValue = $NewsTitle->appendChild($TitleValue);

$test = $doc->save("news/newstest.xml");
print 'done.';
?>

sneaks

2:36 pm on Sep 1, 2005 (gmt 0)

10+ Year Member



i appreciate the effort but the problem with both methods are they add the new content to the end of the xml file instead of nesting within the root tag <news>...