Add values to nodes in an XML file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Nunyah
Forum Newbie
Posts: 7
Joined: Sat Jul 01, 2006 7:08 pm

Add values to nodes in an XML file

Post by Nunyah »

Hey guys, trying to learn how to use XML with php and while there's lots of information in how to parse and (re)write a xml file, I cannot find information that explains how to search up a child node, adding a new value to it.

Small example:

Code: Select all

<webconfig>
<newsperpage>10</newsperpage>
</webconfig>
I guess a clumsy way of solving it would be to rewrite it all each time i edit the settings but it's supposed to contain a dusin of settings at least..
I'm using SimpleXML.

Thanks in advance.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Does your server support DOM XML?
Nunyah
Forum Newbie
Posts: 7
Joined: Sat Jul 01, 2006 7:08 pm

Post by Nunyah »

Yes, it does.
Seeing the documentation, could i search up the node by doing a get_elements_by_tagname() and from there use set_attribute_node?
I cannot really find any examples in how to rewrite a new value to a node in an xml file. You'd think this was a pretty common operation? ..
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

if my value you mean the bit in bold below:
<tagName>value</tagName>

then I'm pretty sure you need to use DomDocument->create_text_node
The following code assumes that the PHP DOM works the same as the javascript one:

Code: Select all

$d = domxml_open_mem($xml);
$tags = $d->get_elements_by_tagname('newsperpage');
// set an existing value
$tags[0]->node_value = $newValue;
// create a value where one doesn't exist
$tags[0]->append_child($d->create_text_node($newValue));
Post Reply