PHP help - writing to an XML file

Soldato
Joined
1 Feb 2006
Posts
8,188
Hi, im writing a script that will accept content from a web form and add it to an xml file. This will make up an RSS feed so I need to be able to add articles to a certain positiion in the document based on tags. In RSS each article is enclosed within <item> tags and the items are preceeded by some header information. Using php, how can i search (for tags) for the correct location in the file where I can add the new content?
I know this is possible using XML DOM and functions like appendChild but I am not sure how this would be done in PHP.
Thanks
 
thanks for the help. I had a look at those links and so far I have came up with this:

Code:
<?php	
	$doc = new DOMDocument();
	
	$doc->load('RSS/sample_rss.xml');
	
	$element = $doc->createElement('item', 'This is the new test element!');
	
	$doc->appendChild($element);
	
	echo $doc->saveXML();
?>

This script adds a new tag at the very end of the file but I need to add it after a tag named 'channel'. How can I do this instead of adding it to the end of the file? Had a look on the PHP site but couldn't find anything.
 
You need to navigate to the position where you want to insert at by using an xpath query or a built in function. Sorry don't know php so can't tell you exactly. Either that or use a function that inserts at a specific position.
 
<?php
$xmlDocument = new DOMDocument('1.0', 'UTF-8');
$loaded = $xmlDocument->loadXML('
<gods>
<god name="Kibo" />
<god name="Xibo" />
</gods>');

$newGod = $xmlDocument->createElement('god');
$newGod->setAttribute('name', 'Maho');

$xpathEvaluator = new DOMXPath($xmlDocument);
$oldGod = $xpathEvaluator->query('/gods/god[@name = "Kibo"]',
$xmlDocument)->item(0);
if ($oldGod != NULL) {
$oldGod->parentNode->insertBefore($newGod, $oldGod->nextSibling);
}

header('Content-Type: application/xml');
echo $xmlDocument->saveXML();
?>
 
No need for XPath. You append via node (not always from the root,) so something like this:

PHP:
$item = $dom->createElement('item');
$pubDate = $dom->createElement('pubDate', date('r', $timestamp)); // Silly example

$item->appendChild($pubDate);

<item>
<pubDate>Thu, 29 Mar 2007 23:28:07 +0100</pubDate>
</item>

*Should work; untested—but you get the idea*
 
Oh, and then in your case it would be (ignore my previous post, I guess):

PHP:
$root = $doc->getElementsByTagName('channel')->item(0);
$element = $doc->createElement('item', 'This is the new test element!');
$root->appendChild($element);
echo $doc->saveXML();

This should work.
 
cool that's what I was hunting gogle for ie getelementsbytagname which is the same function as .NET, I guess they all derive from some w3c standard. can use getreferencebyID as well then if element is ref'd in DTD
 
Back
Top Bottom