A community in which webmasters can ask for help with topics such as PHP coding , MySQL , IT jobs, web design, IT security.
Current location:homephp forumphp talk in 2009 yearHow do I add new elements to XML using PHP DOM deeper than the root? - page 1
User InfoPosts
How do I add new elements to XML using PHP DOM deeper than the root?#1
All of the examples I can find online about this involve simply adding content to an XML file at the document root, but I really need to do it deeper than that.

My XML file is simple, I have:

<?xml v1 etc>
<channel>
<screenshots>
<item>
<title>Image Title</title>
<link>www.link.com/image.jpg</link>
</item>
</screenshots>
</channel>


All I want to be able to do is add new "item" elements, each with a title and link. I know I need to be using PHP DOM, but I(m stumped as to how to code it so that it adds data within "screenshots" rather than overwriting the whole document. I have a suspicion I may need to use XPath too, but I have no idea how!

The code I have pieced together from online examples looks like this (but I(m certain it(s wrong)

$newshottitle = "My new screenshot";
$newshotlink = "http://www.image.com/image.jpg";

$dom = newDomDocument;
$dom->formatOutput = true;
$dom->load("../xml/screenshots.xml");

$dom->getElementsByTagName("screenshots");
$t = $dom->createElement("item");
$t = $dom->createElement("title");
$t->appendChild($dom->createTextNode("$newshottitle"));

$l = $dom->createElement("link");
$l->appendChild($dom->createTextNode("$newshotlink"));

$dom->save("../xml/screenshots.xml");

posted date: 2009-04-07 10:54:00


Re: How do I add new elements to XML using PHP DOM deeper than the root?#2
I had made out the solution of this problem. click to view my topic...

hope that hepls.

posted date: 2009-04-07 10:54:01


Re: How do I add new elements to XML using PHP DOM deeper than the root?#3
adding content to an XML file at the document root, but I really need to do it deeper than that.You(re not adding content anywhere at the moment! You create <title> and <link> element nodes with text in, then you do nothing with them. You should be passing them into ‘appendChild’ on the <item> element node (which also you are currently creating and immediately throwing away by not assigning it to a variable).Here(s a starting-point:$screenshots= $dom->getElementsByTagName("screenshots")[0];$title= $dom->createElement("title");$title->appendChild($dom->createTextNode($newshottitle));$item= $dom->createElement("item");$item->appendChild($title);$screenshots->appendChild($item);

posted date: 2009-04-07 11:43:00


Re: How do I add new elements to XML using PHP DOM deeper than the root?#4
Thanks bobince, I've found that I've become confused by the various versions of PHP documentation out there, as well as there being both DOM and DOM XML examples to choose from.

posted date: 2009-04-07 11:46:00


select page: « 1 »
Copyright ©2008-2017 www.momige.com, all rights reserved.