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!
I want my code to add children within my xml file if the queried tag does not exist, but I can't figure how to add it into the proper section within the nodes.
$newText = 'New Text';
$entries = $this->getQuery($query); // does a query using a DOMXPath object
$curTag = $entries->item(0);
if ($curTag == null)
{
echo "No entries found, creating it now...\n";
$node = $this->_doc->createElement($entries, "$newText");
$newnode = $this->_doc->appendChild($node);
return;
}
Of course, there are problems with the code above ($entries is NULL and not a text field), but if you could help me out on this, I would appreciate it! Also, I would prefer to maintain some sort of order (ie maybe use insertBefore(), but if none of the children exist around it, I dont know how to find the 'next best' place to insert the node...
Right, thats what I was meaning when I said it wasn't right . How can I insert the right node in the right location? Do I use something like the above or what?
Define "right location".
createElement() does what its name says, it creates an element. createElement('nameOfTheElement', 'contents of the new element');
appendChild() also does what its name says, if you call $elem->appendChild(...) it appends the given node as a child to $elem.
Last edited by volka on Wed May 30, 2007 9:28 am, edited 1 time in total.
McManCSU wrote:I am assuming that creating a node and appending it will put it after the /abc tag??
if you call $xyz->appendChild($newNode) where $xyz repesents the <xyz> element in your example, yes.
If you call $abc->appendChild($newNode) it will appear "after" <sss>
Ok, we're getting closer. Now, what if no other nodes around it exist, say we want to add <xyz>-><bbb>-><ccc>-><new_node>? Now, I am not sure that the append child will work since there is only one 'common' node (<xyz>)...
In case you are wondering what I am doing, I am creating an interface that will first search for data, then replace/add data from the xml doc. The data is user inputted configurations (from POST array). The reason some of it may or may not be there is because I want to reduce the overhead of adding additional inputs to the configuration pages. So, if it doesn't exist, create it (which is easier said than done it appears)...
Your document has always a so-called "document element" (otherwise it is not an xml document). This element can be accessed by the property documentElement of the DOMDocument object, in your case $this->_doc->documentElement. There is one, exactly one document element.
From there on you can append childs to any element you like. But you must know to which element you want to append a new node. There is no magic function putTheNodeWhereItBelongs()